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
|
amcorrigan/IA-Lab-master
|
gaussFiltOffset.m
|
.m
|
IA-Lab-master/Filters/gaussFiltOffset.m
| 1,775 |
utf_8
|
3c47e3ae95addd318e6d79acb19301e9
|
function fim = gaussFiltOffset(im,frad,offset,boundcon,relsiz)
% N-dimensional Gaussian filtering
% This works by permuting the image rather than the
% kernel so that the filtering is always done along the first dimension,
% which seems to be faster for some reason.
if nargin<5 || isempty(relsiz)
relsiz = 8; % size of the filter relative to the Gaussian radius
end
if nargin<4 || isempty(boundcon)
boundcon = 'replicate';
end
if ~isa(im,'double')
im = double(im);
end
% the number of elements of frad explicitly tells us how many dimensions we
% want to filter, so a scalar would mean only the x-dimension is filtered
siz = odd(relsiz.*frad,'up'); % element-wise in case we've specified different relative sizes in each dimension..
% need to work out which dimensions are to be permuted
totdim = numel(size(im)); % assume we won't be daft enough to use this function for low dimensional images..
ndim = numel(frad);
% allow a filter radius of zero to specify no filtering
pvect = 1:totdim;
pvect(1:ndim) = [ndim,1:(ndim-1)];
fim = im;
% work in reverse order
for ii = ndim:-1:1
fim = permute(fim,pvect);
if frad(ii)>0
n = (0.55:0.1:(siz(ii)+0.45))';
m = (1+siz(ii))/2;
temp1 = exp(-((n-m - offset(ii)).^2)/(2*frad(ii)^2));
kk = sum(reshape(temp1,[10,numel(temp1)/10]),1)';
kk = kk/sum(kk);
fim = imfilter(fim,kk,boundcon);
end
end
end
function out = odd(x,direction)
if nargin<2
direction = 'up';
end
if ~ischar(direction)
if direction>0
direction = 'up';
else
direction = 'down';
end
end
switch direction
case 'up'
out = ceil((x + 1)/2)*2 - 1;
case 'down'
out = floor((x + 1)/2)*2 - 1;
end
end
|
github
|
MelWe/mm-hypothesis-master
|
testvariancebaseddimandTVLIDAR.m
|
.m
|
mm-hypothesis-master/code/testvariancebaseddimandTVLIDAR.m
| 17,901 |
utf_8
|
ce6eaeefa9d22ac2c81927608fc1d80d
|
function testvariancebaseddimandTVLIDAR( testid )
%This file illustrates the variance based intrinsic dimension code and
%total variance functions on the Bridge_87K.txt file
% This is a slight modification of Linda's code to work on neighborhood
% created using k nearest neighbors instead of epsilon balls.
if testid == 8
fnamedata = 'Bridge_87K.txt';
data = dlmread(fnamedata);
x = data(:,1);
y = data(:,2);
z = data(:,3);
xdiam = max(x) - min(x);
ydiam = max(y) - min(y);
zdiam = max(z) - min(z);
maxdiam = sqrt(xdiam^2 + ydiam^2 + zdiam^2);
h1 = figure;
scatter3(x,y,z);
str = sprintf('scatterplot of data for testid %d',testid);
title(str)
% dirname = '/Users/lindaness/Documents/MATLAB/MSVDLinda/testsLIDAR/';
dirname = '/Users/kyacouboudjima/Dropbox (Amherst College)/Research/Computing/LocalCodes/ProjectBased/WiSDM/Current';
fnamescatter = [dirname,sprintf('test%d',testid)];
saveas(h1,[fnamescatter,'.fig']);
saveas(h1,[fnamescatter,'.png']);
varthreshhold = .95; K = 3; epszero = 10^(-12); TVfigs = 1;
radii = (maxdiam)*2.^(-1.*[4:7])
q = length(radii);
fname = [dirname,sprintf('testvarbasedidim testid %d',testid)];
idimfigs = 1;
[ idimsummary,istatssummary,idim,firstscaleindex,scaleprob, scales,consecutive,dense,SG,indG,SSVs] = variancebaseddim( data,radii,K,varthreshhold,epszero,idimfigs,fname );
idimsummary
display('columheadings: idim,firstscaleindex, count');
istatssummary
save(fname,'varthreshhold', 'K', 'radii', 'epszero', 'TVfigs', 'fname');
save(fname,'data','-append');
save(fname, 'idimsummary','istatssummary','idim','firstscaleindex','scaleprob', 'scales','consecutive','dense','SG','indG','SSVs','-append');
[SSVEnergy,idimSSVEnergy,EidimSSVEnergy,TV,ETV,idimTV,EidimTV ] = TotalVarianceFunctions(data,idim,SG,radii,q,scales,indG,TVfigs,fname);
save(fname,'SSVEnergy','idimSSVEnergy','EidimSSVEnergy','TV','ETV','idimTV','EidimTV','-append');
end
end
function [ idimsummary,istatssummary,idim,firstscaleindex,scaleprob, scales,consecutive,dense,SG,indG,SSVs] = variancebaseddim( data,radii,K,varthreshhold,epszero,idimfigs,fname )
%idim plots are shown if idimfigs == 1
%variance function pots are shown if TVfigs == 1
%radii is a decreasing sequence of radiuses determining a sequence of
%balls around each point. The index of each radius is referred to as the
%scale.
[m,n] = size(data); % m data points, n coordinates
maxdim = min(m,n);
q = length(radii);
%This program looks for points with intrinsic dimensions <= K (with respect
%to the family of point neighborhoods specified by radii
cutoff = K*log(K);
%This function computes the intrinsic dimension idim for each point by
%a concentration of variance analysis using varthreshhold (e.g. .95)
%SSVs is an m x maxdim*q matrix of q groups of squared singular values
%of matrices of points in each ball, the matrices are centered so EV = 0
%The squared singular values are then the variances of each centered coordinate.
%PeG is an m x maxdim*q matrix of q groups of discrete probability distriutions
%for each of the m points (relative variances); SG is an m x q matrix of
%total variances for each ball; CumG is an m x maxdim*q matrix of q groups
%of vectors (c1, ..., cn) defining the cumulative distribution for
%(p1,..,pn) so cj = p1 + ... pj
% idim(p) = i, i = minimum over the scales of smallestindex j cj >= varthresshold
%e.g if varthreshhold = .95 ,idim(p) = i if there is a ball (scale) for which
%the sum of the variances of the first i centered coordinates >= .95
%scales is an m xq matrix of 0's and 1's. each row (pt) has 1's at the scales
%i, such that ci >= varthresshold and i = idim(pt)
%i.e. idim is computed by concentration of variance analysis and the
%scales is the set of indices of balls where the variance accumulates to
%the fastest to varthreshhold
%Two summary matrices are computed: idimsummary and istatssummary
%rows of idimsummary (idim value, number of points with idim value)
%i.e. the discrete distribution of idim for the data set
%rows of istats summary (idim value, first scale index, number of points
%with the specified idim value and first scale index.
%i.e. the discrete distribution of idim,firstscale for the data set
%If idimfigs == 1 scatter plots of the data points color-coded by idim
%are computed
%Different Total Variance functions are computed for each point, including
%the SSVEnergy function.
%Summaries of idim statistics are computed; idim and the Total Varianc
%functions are plotted
[ SSVs,dense,ballcount ] = ComputeSSVs( data,radii,cutoff );
M = SSVs;
[ PrG,SG,CumG,indG ] = ProbDistGroups(M,q,maxdim,dense,epszero);
%PrG1599 = PrG(1599,:)
%SG199 = SG(1599,:)
%CumG1599 = CumG(1599,:)
groupdim = n;
t = varthreshhold;
[idim,firstscaleindex, scales,idimG,mxG,scaleprob,consecutive] = idimprob( CumG,q,groupdim,t,indG);
u = unique(idim);
idimsummary = zeros(length(u),2 );
for i = 1:length(u)
ind = find(idim == u(i));
lgth = length(ind);
idimsummary(i,:) = [u(i),lgth];
end
[istats,irhs,ilhs] = unique([idim,firstscaleindex],'rows');
%istatssummary = zeros(length(istats),4);
istatssummary = zeros(length(istats),3);
for i = 1:size(istats,1)
%x = abs(istats(i,1:3));
x = istats(i,1:2);
y = length(find(ilhs == i));
istatssummary(i,:) = [x,y];
end
if idimfigs == 1
ind = find(idim > 0);
m2 = length(ind);
h = figure;
a = [1:m2];
b = idim(ind,:);
scatter(a,b,100);
titlestr = sprintf('ordered points with y coordinate = idim');
if ~length(fname) == 0
fname1 = [fname,'orderedidim','.png'];
saveas(h,fname1);
fname1 = [fname,'orderedidim','.fig'];
saveas(h,fname1);
end
if n == 3
X = data(ind,1); Y = data(ind,2); Z = data(ind,3);
idim2 = idim(ind,:);
firstscaleindex2 = firstscaleindex(ind,:);
h = figure;
colormap(jet(m2));
scatter3(X,Y,Z,10,idim2);
titlestr = sprintf('points color-coded by idim');
title(titlestr);
if ~length(fname) == 0
fname1 = [fname,'idim','.png'];
saveas(h,fname1);
fname1 = [fname,'idim','.fig'];
saveas(h,fname1);
end
h = figure;
colormap(jet(m));
scatter3(X,Y,Z,10,ilhs(ind,:));
%scatter3(X,Y,Z,100,firstscaleindex2);
titlestr = sprintf('points color-coded by lexicographic ordering of idim,firstscaleindex');
title(titlestr);
if ~length(fname) == 0
fname1 = [fname,'lexidim','.png'];
saveas(h,fname1);
fname1 = [fname,'lexidim','.fig'];
saveas(h,fname1);
end
end
end
end
function [SSVEnergy,idimSSVEnergy,EidimSSVEnergy,TV,ETV,idimTV,EidimTV ] = TotalVarianceFunctions(data,idim, SG,radii,q,scales,indG,TVfigs,fname)
%data is an m xn matrix of m data points with n coordinate
%SG is an m x q matrix of total variances for data in each of the q balls
%with radii specified in radius (total variances of the centered data)
%SG entries for a ball are -1 if the intrinsic dimension was not computed for that ball
%due to too few points etc
%scales is an m x q matrix of 0's and 1's specifying the scales at which idim was observed
%for each data point
%indG is an m x q matrix of 0's and 1's specifying the scales for which
%intrinsic dimension was computed
%A variety of total variance functions are computed including the SSVEnergy
%function we computed at WiSDM
%if TVfig == 1, the total variance functions are plotted for the subset of
%points for which intrinsic dimension was computed.
[m,n] = size(data);
%SG is an m x q matrix containg the total variances for each ball
%(or -1's for the ball where SG and hence the intrinsic dimension were
%not computed
%Compute different Versions of Total Variance Functions
%TV sum of total variances over the relevant balls
TV = sum(SG.*indG,2);
ETV = TV./sum(indG,2); %m x 1 average of total variances of relevant balls
idimTV = sum(scales.*SG,2); %sum of scale variances for idim scales
%total variance for each of these scale is concentrated near idim scales
EidimTV = idimTV./sum(scales,2); %Expected Value over the scales where
%local idim = idim for the point
R = repmat(radii.^2,m,1);
RelSG = SG./R; %RelSG total variances for each ball are normalized by
%dividing by the square of the radius; functions analagous to above are
%computed from the relative variances.
SSVEnergy =sum(RelSG,2) ; %This is the SSVEnergy function computed at WiSDM
idimSSVEnergy = sum(scales.*RelSG,2);
EidimSSVEnergy = idimSSVEnergy./sum(scales,2);
if TVfigs == 1
ind = find(idim > 0);
SG = SG(ind,:);
m = size(data(ind,:),1);
%h = figure;
%x = 1:m;
%hold on
%for i = 1:q
%plot(x,SG(:,i));
%end
%titlestr = sprintf('Total Variance Curves for each scale');
%title(titlestr)
%hold off
if n == 3
X = data(ind,1); Y = data(ind,2); Z = data(ind,3);
TV = TV(ind,:);
idimTV = idimTV(ind,:);
EidimTV = EidimTV(ind,:);
SSVEnergy = SSVEnergy(ind,:);
idimSSVEnergy = idimSSVEnergy(ind,:);
EidimSSVEnergy = EidimSSVEnergy(ind,:);
h = figure;
colormap(jet(length(ind)));
scatter3(X,Y,Z,100,TV);
titlestr = sprintf('points color-coded by sum of Total Variances over scales where idim was computed');
title(titlestr);
if ~length(fname) == 0
fname1 = [fname,'TV','.png'];
saveas(h,fname1);
fname1 = [fname,'TV','.fig'];
saveas(h,fname1);
end
h = figure;
colormap(jet(length(ind)));
scatter3(X,Y,Z,100,idimTV);
titlestr = sprintf('points color-coded by sum of Total Variance over idim scales for each point') ;
title(titlestr);
if ~length(fname) == 0
fname1 = [fname,'idimTV','.png'];
saveas(h,fname1);
fname1 = [fname,'idimTV','.fig'];
saveas(h,fname1);
end
h = figure;
colormap(jet(length(ind)));
scatter3(X,Y,Z,100,EidimTV);
titlestr = sprintf('points color-coded by EV of Total Variance over idim scales for each point') ;
title(titlestr);
if ~length(fname) == 0
fname1 = [fname,'EidimTV','.png'];
saveas(h,fname1);
fname1 = [fname,'EidimTV','.fig'];
saveas(h,fname1);
end
h = figure;
colormap(jet(length(ind)));
scatter3(X,Y,Z,100,SSVEnergy);
titlestr = sprintf('SSVEnergy - points color-coded by sum of normalized total variances over scales where idim was computed') ;
title(titlestr);
if ~length(fname) == 0
fname1 = [fname,'SSVEnergy','.png'];
saveas(h,fname1);
fname1 = [fname,'SSVEnergy','.fig'];
saveas(h,fname1);
end
h = figure;
colormap(jet(length(ind)));
scatter3(X,Y,Z,100,idimSSVEnergy);
titlestr = sprintf('idmSSVEnergy - points color-coded by sum of normalized total variances over idim scales') ;
title(titlestr);
if ~length(fname) == 0
fname1 = [fname,'idimSSVEnergy','.png'];
saveas(h,fname1);
fname1 = [fname,'idimSSVEnergy','.fig'];
saveas(h,fname1);
end
h = figure;
colormap(jet(length(ind)));
scatter3(X,Y,Z,100,EidimSSVEnergy);
titlestr = sprintf('EidmSSVEnergy - points color-coded by EV of normalized total variances over idim scales') ;
title(titlestr);
if ~length(fname) == 0
fname1 = [fname,'EidimSSVEnergy','.png'];
saveas(h,fname1);
fname1 = [fname,'EidimSSVEnergy','.fig'];
saveas(h,fname1);
end
end
end
end
function [ SSVs,dense,ballcount ] = ComputeSSVs( data,radii,cutoff )
% data is an m x n matrix, whose rows are the data
%r is a 1 x q list of decreasing radii (e.g 2^0, 2^(-1), 2^(-2), ....);
%This function computes the squared singular values for each point p and each
%subset d(p,r) of data points at distance <= r from data point p
%Results are returned in the m x q*maxdim matrix SSVs, maxdim = min(m,n);
%For the ith data point p = data(i,:)
%SSVs for p and d(p,r(j)) are in row i, columns [1:maxdim] + maxdim*(j-1)
%SSVs are not computed if |d(p,r)| < cutoff, instead -1's are stored in SSVs \
%dense is an m x q matrix of 0's and 1's
%dense(i,j) = |d(p,r(j))| < cutoff
[m,n] = size(data);
q = length(radii);
%maxdim is the maximum number of non-zero singular values
maxdim = min(m,n);
%dense(i,j) = 1 if |d(p,r)| > cutoff else 0, p = data(i,:)
dense = ones(m,q);
SSVs = -1*ones(m,q*maxdim);
ballcount = zeros(m,q);
%for each point
for i = 1:m
if mod(i,1000) == 0
i
end
p = data(i,:);
ballmembership = zeros(m,q);
for j = 1:q
r = radii(j);
[b,B] = ball(data,p,r);
ballmembership(:,j) = B;
%compute EV of b and translate by -EV so EV(c) = 0;
c = center(b);
cardc = size(c,1);
if cardc > cutoff
s = svd(c);
sq = s.*s;
inds2 = [1:maxdim] + maxdim*(j-1);
SSVs(i,inds2) = sq;
else
dense(i,j) = 0;
end
end
ballcount(i,:) = sum(ballmembership);
end
end
function [v,B] = ball( data,p,r)
%% p=center; r=radius %%
%This functions finds the data points in the ball of radius r
%centered at p.
[m,n] = size(data);
x = sqrt(sum((data- ones(m,1)*p).^2,2));
B= x < r*ones(m,1);
v=data(B,:);
end
function [ centereddata ] = center( data )
%UNTITLED4 Summary of this function goes here
% Detailed explanation goes here
[m,n] = size(data);
EV = (1/m)*sum(data);
centereddata = data - ones(m,1)*EV;
end
function [ PrG,SG,CumG,indG ] = ProbDistGroups(M,q,maxdim,dense,epszero)
%M is an m x q*maxdim matrix
%dense is an m x q matrix
%epszero very small and positive and used to test for zero e.g 10^(-12)
%SG is m x q; PrG and SG are m x q*maxdim; indG is m x q
%For the jth group of maxdim columns, for each row i, if dense(i,j) == 1 and
%if the entries are >=0 with positive sum (> epszero) , indG(i,j) = 1 and
%the rowsum,probability distribution, and cumlative probability distribution
%of the row are computed and stored in the matrices SG, PrG and CumG.
%for the other rows in the group indG = 0 and the entries of
%SG, PrG and CumG are -1's.
%if M does not have q*maxdim columns PrG,SG,CumG have -1 entries and inG = 0
[m,n] = size(M);
PrG = -1*ones(m,n);
CumG = -1*ones(m,n);
SG = -1*ones(m,q);
indG = zeros(m,q);
if n == q*maxdim
for j = 1:q
inddense = find(dense(:,j) == 1);
indj = [1:maxdim] + maxdim*(j-1);
[ Pr,S,Cum,ind ] = Probdist(M(inddense,indj),epszero);
PrG(inddense,indj) = Pr;
SG(inddense,j) = S;
CumG(inddense,indj) = Cum;
indG(inddense(ind),j) = 1;
end
end
end
function [ Pr,S,Cum,ind ] = Probdist(M,epszero)
%M is a m x n matrix
%S is an m x 1 matrix; Cum and Pr are m x n matrices.
%S,Cum,Pr are initialized to -1;
%for the rows of M which are non-negative with positive sum (> epszero)
%S is the sum of the row
%Pr is the discrete probability distribution determined by the row
%Cum is the cumulative distribution determined by the row
%Example row = [1,2,3]; S = 6, Pr = [1/6,2/6,3/6], Cum = [1/6,1/2,1]
%For the other rows of M, the entries of S, Pr, and Cu are -1.
%ind is the index of the non-negative rows with positive sum
[m,n] = size(M);
S = -1*ones(m,1);
Pr = -1*ones(m,n);
Cum = -1*ones(m,n);
nonneg = M >= 0;
possum = sum(M,2);
N = sum(nonneg,2);
ind = find(N == n & possum > epszero);
S(ind,:) = sum(M(ind,:),2);
k = length(ind);
if k > 0
Tmp = zeros(k,1);
for i = 1:n
Pr(ind,i) = M(ind,i)./S(ind,1);
Tmp = Tmp + Pr(ind,i);
Cum(ind,i) = Tmp;
end
end
end
function [idim,firstscaleindex, scales,idimG,mxG,scaleprob,consecutive] = idimprob( CumG,q,groupdim,t,indG)
%CumG is a matrix whose rows are q groups of cumulative distributions
%of size groupdim
%t is a threshhold 0 <= t <= 1
%The function returns column index of the first element in each row
%which is >= t; if no such index exists, the function returns -1.
[m,n] = size(CumG);
if ~(n == q*groupdim)
idim = [];
firstscaleindex = [];
scales = [];
idimG = [];
mxG = [];
scaleprob = [];
consecutive = [];
display('in idimprob -- CumG does not have the expected number of columns');
else
idim = -1*ones(m,1);
firstscaleindex = -1*ones(m,1);
scales = zeros(m,q);
idimG = -1*ones(m,q);
mxG = -1*ones(m,q);
scaleprob = -1*ones(m,1);
consecutive = -1*ones(m,1);
for j = 1:q
ind = groupdim*(j-1) + [1:groupdim];
C = CumG(:,ind);
D = C >= t;
%find first index in each row where C >= t
[mx,ind] = max(D,[],2);
for i = 1:m
if mx(i) == 1
idimG(i,j) = ind(i,1);
mxG(i,j) = C(i,ind(i));
elseif mx(i) == 0
idimG(i,j) = -1;
mxG(i,j) = -1;
end
end
%col = mxG(:,j)
end
end
%The intrinsic dimension for a point is the minimum of the intrinsic dimensions for
%each scale for which the intrinsic dimension is computed.
%If it is not computed at any scale idim = -1.
for i = 1:m
ind1 = find(indG(i,:) == 1);
if length(ind1) > 0
idim(i,1) = min(idimG(i,ind1));
indscales = find(idimG(i,:) == idim(i,1));
scales(i,indscales) = 1;
scaleprob(i,1) = length(indscales)/length(ind1);
if indscales == indscales(1) - 1 + [1:length(indscales)]
consecutive(i,1) = 1;
end
firstscaleindex(i,1) = indscales(1);
end
end
end
|
github
|
MelWe/mm-hypothesis-master
|
testvariancebaseddimandTV.m
|
.m
|
mm-hypothesis-master/code/testvariancebaseddimandTV.m
| 18,780 |
utf_8
|
83380d1bbcb2228f43ae70132ada3231
|
function testvariancebaseddimandTV( testid )
%This file illustrates the variance based intrinsic dimension code and
%total variance functions.
% a variant of the geodesic minimal spanning tree (GMST) to estimate
% the intrinsic dimension and entropy of the manifold on which the
% data lie.
% Detailed explanation goes here
if testid == 1
varthreshhold = .95 ;K = 3; rgparam = 5; sampleparam = 800;radii = 2:-.1:.1; epszero = 10^(-12); TVfigs = 1; fname = 'test1';
q = length(radii);
[ sample,spheresample,linesample,samplesize ] = ExampleUpdated( sampleparam,rgparam);
sizeoflinesample = size(linesample)
sizeofspheresample = size(spheresample)
data = sample;
idimfigs = 1;
[ idimsummary,istatssummary,idim,firstscaleindex,scaleprob, scales,consecutive,dense,SG,indG,SSVs] = variancebaseddim( data,radii,K,varthreshhold,epszero,idimfigs,fname );
idimsummary
display('columheadings: idim,firstscaleindex, count');
istatssummary
[SSVEnergy,idimSSVEnergy,EidimSSVEnergy,TV,ETV,idimTV,EidimTV ] = TotalVarianceFunctions(data,idim,SG,radii,q,scales,indG,TVfigs,fname);
save(fname,'varthreshhold', 'K', 'rgparam', 'sampleparam', 'radii', 'epszero', 'TVfigs','q', 'fname');
save(fname,'sample','spheresample','linesample','samplesize','sizeoflinesample','sizeofspheresample','-append');
save(fname, 'idimsummary','istatssummary','idim','firstscaleindex','scaleprob', 'scales','consecutive','dense','SG','indG','SSVs','-append');
save(fname,'SSVEnergy','idimSSVEnergy','EidimSSVEnergy','TV','ETV','idimTV','EidimTV','-append');
elseif testid == 2
varthreshhold = .95 ;K = 3; rgparam = 5; sampleparam = 800;ind = 0:10; radii = 2:-.1:.1; epszero = 10^(-12); TVfigs = 1; fname = 'test2';
q = length(radii);
[ sample,spheresample,linesample,samplesize ] = ExampleUpdated( sampleparam,rgparam);
sizeoflinesample = size(linesample)
sizeofspheresample = size(spheresample)
data = sample;
idimfigs = 1;
[ idimsummary,istatssummary,idim,firstscaleindex,scaleprob, scales,consecutive,dense,SG,indG,SSVs] = variancebaseddim( data,radii,K,varthreshhold,epszero,idimfigs,fname );
idimsummary
display('columheadings: idim,firstscaleindex, count');
istatssummary
[SSVEnergy,idimSSVEnergy,EidimSSVEnergy,TV,ETV,idimTV,EidimTV ] = TotalVarianceFunctions(data,idim,SG,radii,q,scales,indG,TVfigs,fname);
save(fname,'varthreshhold', 'K', 'rgparam', 'sampleparam', 'radii', 'epszero', 'TVfigs', 'fname');
save(fname,'sample','spheresample','linesample','samplesize','sizeoflinesample','sizeofspheresample','-append');
save(fname, 'idimsummary','istatssummary','idim','firstscaleindex','scaleprob', 'scales','consecutive','dense','SG','indG','SSVs','-append');
save(fname,'SSVEnergy','idimSSVEnergy','EidimSSVEnergy','TV','ETV','idimTV','EidimTV','-append');
end
end
function [ sample,spheresample,linesample,samplesize ] = ExampleUpdated( sampleparam,rgparam)
%This function generates random samples from a figure consisting of a sphere of
%radius 1/2 and a through the origin
%
%x = rsin(theta)cos(phi)
%y = rsin(theta)sin(phi)
%z = rcos(theta)
%theta in [0,pi]
%phi in [0,2*pi]
rng(rgparam);
theta = pi*rand(floor(pi*sampleparam),1);
phi = 2*pi*rand(floor(pi*sampleparam),1);
spheresample = [.5*sin(theta).*cos(phi),.5*sin(theta).*sin(phi),.5*cos(theta)];
sz = floor(.5*sampleparam);
r = rand(sz,1);
r = 2*(r - .5*ones(sz,1));
ind = find(r >= .5 | r <= -.5);
linesample = zeros(length(ind),3);
linesample(:,1) = r(ind);
sample = [spheresample;linesample];
%add two points on the intersection of the line and the spere
%these points should have intrinisic dimension 3
sample = [sample;.5,0,0;-.5,0,0];
samplesize = length(sample);
x = sample(:,1); y = sample(:,2); z = sample(:,3);
scatter3(x,y,z)
end
function [ idimsummary,istatssummary,idim,firstscaleindex,scaleprob, scales,consecutive,dense,SG,indG,SSVs] = variancebaseddim( data,radii,K,varthreshhold,epszero,idimfigs,fname )
%idim plots are shown if idimfigs == 1
%variance function pots are shown if TVfigs == 1
%radii is a decreasing sequence of radiuses determining a sequence of
%balls around each point. The index of each radius is referred to as the
%scale.
[m,n] = size(data); % m data points, n coordinates
maxdim = min(m,n);
q = length(radii);
%This program looks for points with intrinsic dimensions <= K (with respect
%to the family of point neighborhoods specified by radii
cutoff = K*log(K);
%This function computes the intrinsic dimension idim for each point by
%a concentration of variance analysis using varthreshhold (e.g. .95)
%SSVs is an m x maxdim*q matrix of q groups of squared singular values
%of matrices of points in each ball, the matrices are centered so EV = 0
%The squared singular values are then the variances of each centered coordinate.
%PeG is an m x maxdim*q matrix of q groups of discrete probability distriutions
%for each of the m points (relative variances); SG is an m x q matrix of
%total variances for each ball; CumG is an m x maxdim*q matrix of q groups
%of vectors (c1, ..., cn) defining the cumulative distribution for
%(p1,..,pn) so cj = p1 + ... pj
% idim(p) = i, i = minimum over the scales of smallestindex j cj >= varthresshold
%e.g if varthreshhold = .95 ,idim(p) = i if there is a ball (scale) for which
%the sum of the variances of the first i centered coordinates >= .95
%scales is an m xq matrix of 0's and 1's. each row (pt) has 1's at the scales
%i, such that ci >= varthresshold and i = idim(pt)
%i.e. idim is computed by concentration of variance analysis and the
%scales is the set of indices of balls where the variance accumulates to
%the fastest to varthreshhold
%Two summary matrices are computed: idimsummary and istatssummary
%rows of idimsummary (idim value, number of points with idim value)
%i.e. the discrete distribution of idim for the data set
%rows of istats summary (idim value, first scale index, number of points
%with the specified idim value and first scale index.
%i.e. the discrete distribution of idim,firstscale for the data set
%If idimfigs == 1 scatter plots of the data points color-coded by idim
%are computed
%Different Total Variance functions are computed for each point, including
%the SSVEnergy function.
%Summaries of idim statistics are computed; idim and the Total Varianc
%functions are plotted
[ SSVs,dense,ballcount ] = ComputeSSVs( data,radii,cutoff );
M = SSVs;
[ PrG,SG,CumG,indG ] = ProbDistGroups(M,q,maxdim,dense,epszero);
%PrG1599 = PrG(1599,:)
%SG199 = SG(1599,:)
%CumG1599 = CumG(1599,:)
groupdim = n;
t = varthreshhold;
[idim,firstscaleindex, scales,idimG,mxG,scaleprob,consecutive] = idimprob( CumG,q,groupdim,t,indG);
u = unique(idim);
idimsummary = zeros(length(u),2 );
for i = 1:length(u)
ind = find(idim == u(i));
lgth = length(ind);
idimsummary(i,:) = [u(i),lgth];
end
[istats,irhs,ilhs] = unique([idim,firstscaleindex],'rows');
%istatssummary = zeros(length(istats),4);
istatssummary = zeros(length(istats),3);
for i = 1:size(istats,1)
%x = abs(istats(i,1:3));
x = istats(i,1:2);
y = length(find(ilhs == i));
istatssummary(i,:) = [x,y];
end
if idimfigs == 1
ind = find(idim > 0);
m2 = length(ind);
h = figure;
a = [1:m2];
b = idim(ind,:);
scatter(a,b,100);
titlestr = sprintf('ordered points with y coordinate = idim');
if ~length(fname) == 0
fname1 = [fname,'orderedidim','.png'];
saveas(h,fname1);
end
if n == 3
X = data(ind,1); Y = data(ind,2); Z = data(ind,3);
idim2 = idim(ind,:);
firstscaleindex2 = firstscaleindex(ind,:);
h = figure;
colormap(jet(m2));
scatter3(X,Y,Z,100,idim2);
titlestr = sprintf('points color-coded by idim');
title(titlestr);
if ~length(fname) == 0
fname1 = [fname,'idim','.png'];
saveas(h,fname1);
end
h = figure;
colormap(jet(m));
scatter3(X,Y,Z,100,ilhs(ind,:));
%scatter3(X,Y,Z,100,firstscaleindex2);
titlestr = sprintf('points color-coded by lexicographic ordering of idim,firstscaleindex');
title(titlestr);
if ~length(fname) == 0
fname1 = [fname,'lexidim','.png'];
saveas(h,fname1);
end
end
end
end
function [SSVEnergy,idimSSVEnergy,EidimSSVEnergy,TV,ETV,idimTV,EidimTV ] = TotalVarianceFunctions(data,idim, SG,radii,q,scales,indG,TVfigs,fname)
%data is an m xn matrix of m data points with n coordinate
%SG is an m x q matrix of total variances for data in each of the q balls
%with radii specified in radius (total variances of the centered data)
%SG entries for a ball are -1 if the intrinsic dimension was not computed for that ball
%due to too few points etc
%scales is an m x q matrix of 0's and 1's specifying the scales at which idim was observed
%for each data point
%indG is an m x q matrix of 0's and 1's specifying the scales for which
%intrinsic dimension was computed
%A variety of total variance functions are computed including the SSVEnergy
%function we computed at WiSDM
%if TVfig == 1, the total variance functions are plotted for the subset of
%points for which intrinsic dimension was computed.
[m,n] = size(data);
%SG is an m x q matrix containg the total variances for each ball
%(or -1's for the ball where SG and hence the intrinsic dimension were
%not computed
%Compute different Versions of Total Variance Functions
%TV sum of total variances over the relevant balls
TV = sum(SG.*indG,2);
ETV = TV./sum(indG,2); %m x 1 average of total variances of relevant balls
idimTV = sum(scales.*SG,2); %sum of scale variances for idim scales
%total variance for each of these scale is concentrated near idim scales
EidimTV = idimTV./sum(scales,2); %Expected Value over the scales where
%local idim = idim for the point
R = repmat(radii.^2,m,1);
RelSG = SG./R; %RelSG total variances for each ball are normalized by
%dividing by the square of the radius; functions analagous to above are
%computed from the relative variances.
SSVEnergy =sum(RelSG,2) ; %This is the SSVEnergy function computed at WiSDM
idimSSVEnergy = sum(scales.*RelSG,2);
EidimSSVEnergy = idimSSVEnergy./sum(scales,2);
if TVfigs == 1
ind = find(idim > 0);
SG = SG(ind,:);
m = size(data(ind,:),1);
%h = figure;
%x = 1:m;
%hold on
%for i = 1:q
%plot(x,SG(:,i));
%end
%titlestr = sprintf('Total Variance Curves for each scale');
%title(titlestr)
%hold off
if n == 3
X = data(ind,1); Y = data(ind,2); Z = data(ind,3);
h = figure;
colormap(jet(m));
scatter3(X,Y,Z,100,TV);
titlestr = sprintf('points color-coded by sum of Total Variances over scales where idim was computed');
title(titlestr);
if ~length(fname) == 0
fname1 = [fname,'TV','.png'];
saveas(h,fname1);
end
h = figure;
colormap(jet(m));
scatter3(X,Y,Z,100,idimTV);
titlestr = sprintf('points color-coded by sum of Total Variance over idim scales for each point') ;
title(titlestr);
if ~length(fname) == 0
fname1 = [fname,'idimTV','.png'];
saveas(h,fname1);
end
h = figure;
colormap(jet(m));
scatter3(X,Y,Z,100,EidimTV);
titlestr = sprintf('points color-coded by EV of Total Variance over idim scales for each point') ;
title(titlestr);
if ~length(fname) == 0
fname1 = [fname,'EidimTV','.png'];
saveas(h,fname1);
end
h = figure;
colormap(jet(m));
scatter3(X,Y,Z,100,SSVEnergy);
titlestr = sprintf('SSVEnergy - points color-coded by sum of normalized total variances over scales where idim was computed') ;
title(titlestr);
if ~length(fname) == 0
fname1 = [fname,'SSVEnergy','.png'];
saveas(h,fname1);
end
h = figure;
colormap(jet(m));
scatter3(X,Y,Z,100,idimSSVEnergy);
titlestr = sprintf('idmSSVEnergy - points color-coded by sum of normalized total variances over idim scales') ;
title(titlestr);
if ~length(fname) == 0
fname1 = [fname,'idimSSVEnergy','.png'];
saveas(h,fname1);
end
h = figure;
colormap(jet(m));
scatter3(X,Y,Z,100,EidimSSVEnergy);
titlestr = sprintf('EidmSSVEnergy - points color-coded by EV of normalized total variances over idim scales') ;
title(titlestr);
if ~length(fname) == 0
fname1 = [fname,'EidimSSVEnergy','.png'];
saveas(h,fname1);
end
end
end
end
function [ SSVs,dense,ballcount ] = ComputeSSVs( data,radii,cutoff )
% data is an m x n matrix, whose rows are the data
%r is a 1 x q list of decreasing radii (e.g 2^0, 2^(-1), 2^(-2), ....);
%This function computes the squared singular values for each point p and each
%subset d(p,r) of data points at distance <= r from data point p
%Results are returned in the m x q*maxdim matrix SSVs, maxdim = min(m,n);
%For the ith data point p = data(i,:)
%SSVs for p and d(p,r(j)) are in row i, columns [1:maxdim] + maxdim*(j-1)
%SSVs are not computed if |d(p,r)| < cutoff, instead -1's are stored in SSVs \
%dense is an m x q matrix of 0's and 1's
%dense(i,j) = |d(p,r(j))| < cutoff
[m,n] = size(data);
q = length(radii);
%maxdim is the maximum number of non-zero singular values
maxdim = min(m,n);
%dense(i,j) = 1 if |d(p,r)| > cutoff else 0, p = data(i,:)
dense = ones(m,q);
SSVs = -1*ones(m,q*maxdim);
ballcount = zeros(m,q);
%for each point
for i = 1:m
p = data(i,:);
ballmembership = zeros(m,q);
for j = 1:q
r = radii(j);
[b,B] = ball(data,p,r);
ballmembership(:,j) = B;
%compute EV of b and translate by -EV so EV(c) = 0;
c = center(b);
cardc = size(c,1);
if cardc > cutoff
s = svd(c);
sq = s.*s;
inds2 = [1:maxdim] + maxdim*(j-1);
SSVs(i,inds2) = sq;
else
dense(i,j) = 0;
end
end
ballcount(i,:) = sum(ballmembership);
end
% size(SSVs)
% scatter3(data(:,1),data(:,2),data(:,3),100, SSVs)
end
function [v,B] = ball( data,p,r)
%% p=center; r=radius %%
%This functions finds the data points in the ball of radius r
%centered at p.
[m,n] = size(data);
x = sqrt(sum((data- ones(m,1)*p).^2,2));
B= x < r*ones(m,1);
v=data(B,:);
end
function [ centereddata ] = center( data )
%UNTITLED4 Summary of this function goes here
% Detailed explanation goes here
[m,n] = size(data);
EV = (1/m)*sum(data);
centereddata = data - ones(m,1)*EV;
end
function [ PrG,SG,CumG,indG ] = ProbDistGroups(M,q,maxdim,dense,epszero)
%M is an m x q*maxdim matrix
%dense is an m x q matrix
%epszero very small and positive and used to test for zero e.g 10^(-12)
%SG is m x q; PrG and SG are m x q*maxdim; indG is m x q
%For the jth group of maxdim columns, for each row i, if dense(i,j) == 1 and
%if the entries are >=0 with positive sum (> epszero) , indG(i,j) = 1 and
%the rowsum,probability distribution, and cumlative probability distribution
%of the row are computed and stored in the matrices SG, PrG and CumG.
%for the other rows in the group indG = 0 and the entries of
%SG, PrG and CumG are -1's.
%if M does not have q*maxdim columns PrG,SG,CumG have -1 entries and inG = 0
[m,n] = size(M);
PrG = -1*ones(m,n);
CumG = -1*ones(m,n);
SG = -1*ones(m,q);
indG = zeros(m,q);
if n == q*maxdim
for j = 1:q
inddense = find(dense(:,j) == 1);
indj = [1:maxdim] + maxdim*(j-1);
[ Pr,S,Cum,ind ] = Probdist(M(inddense,indj),epszero);
PrG(inddense,indj) = Pr;
SG(inddense,j) = S;
CumG(inddense,indj) = Cum;
indG(inddense(ind),j) = 1;
end
end
end
function [ Pr,S,Cum,ind ] = Probdist(M,epszero)
%M is a m x n matrix
%S is an m x 1 matrix; Cum and Pr are m x n matrices.
%S,Cum,Pr are initialized to -1;
%for the rows of M which are non-negative with positive sum (> epszero)
%S is the sum of the row
%Pr is the discrete probability distribution determined by the row
%Cum is the cumulative distribution determined by the row
%Example row = [1,2,3]; S = 6, Pr = [1/6,2/6,3/6], Cum = [1/6,1/2,1]
%For the other rows of M, the entries of S, Pr, and Cu are -1.
%ind is the index of the non-negative rows with positive sum
[m,n] = size(M);
S = -1*ones(m,1);
Pr = -1*ones(m,n);
Cum = -1*ones(m,n);
nonneg = M >= 0;
possum = sum(M,2);
N = sum(nonneg,2);
ind = find(N == n & possum > epszero);
S(ind,:) = sum(M(ind,:),2);
k = length(ind);
if k > 0
Tmp = zeros(k,1);
for i = 1:n
Pr(ind,i) = M(ind,i)./S(ind,1);
Tmp = Tmp + Pr(ind,i);
Cum(ind,i) = Tmp;
end
end
end
function [idim,firstscaleindex, scales,idimG,mxG,scaleprob,consecutive] = idimprob( CumG,q,groupdim,t,indG)
%CumG is a matrix whose rows are q groups of cumulative distributions
%of size groupdim
%t is a threshhold 0 <= t <= 1
%The function returns column index of the first element in each row
%which is >= t; if no such index exists, the function returns -1.
[m,n] = size(CumG);
if ~(n == q*groupdim)
idim = [];
firstscaleindex = [];
scales = [];
idimG = [];
mxG = [];
scaleprob = [];
consecutive = [];
display('in idimprob -- CumG does not have the expected number of columns');
else
idim = -1*ones(m,1);
firstscaleindex = -1*ones(m,1);
scales = zeros(m,q);
idimG = -1*ones(m,q);
mxG = -1*ones(m,q);
scaleprob = -1*ones(m,1);
consecutive = -1*ones(m,1);
for j = 1:q
ind = groupdim*(j-1) + [1:groupdim];
C = CumG(:,ind);
D = C >= t;
%find first index in each row where C >= t
[mx,ind] = max(D,[],2);
for i = 1:m
if mx(i) == 1
idimG(i,j) = ind(i,1);
mxG(i,j) = C(i,ind(i));
elseif mx(i) == 0
idimG(i,j) = -1;
mxG(i,j) = -1;
end
end
%col = mxG(:,j)
end
end
%The intrinsic dimension for a point is the minimum of the intrinsic dimensions for
%each scale for which the intrinsic dimension is computed.
%If it is not computed at any scale idim = -1.
for i = 1:m
ind1 = find(indG(i,:) == 1);
if length(ind1) > 0
idim(i,1) = min(idimG(i,ind1));
indscales = find(idimG(i,:) == idim(i,1));
scales(i,indscales) = 1;
scaleprob(i,1) = length(indscales)/length(ind1);
if indscales == indscales(1) - 1 + [1:length(indscales)]
consecutive(i,1) = 1;
end
firstscaleindex(i,1) = indscales(1);
end
end
end
|
github
|
MelWe/mm-hypothesis-master
|
idimprob.m
|
.m
|
mm-hypothesis-master/code/vidim2code/idimprob.m
| 1,907 |
utf_8
|
ad428ae3d0eed13d1868b9a7f0230b9d
|
function [idim,firstscaleindex, scales,idimG,mxG,scaleprob,consecutive] = idimprob( CumG,q,groupdim,t,indG)
%CumG is a matrix whose rows are q groups of cumulative distributions
%of size groupdim
%t is a threshhold 0 <= t <= 1
%The function returns column index of the first element in each row
%which is >= t; if no such index exists, the function returns -1.
[m,n] = size(CumG);
if ~(n == q*groupdim)
idim = [];
firstscaleindex = [];
scales = [];
idimG = [];
mxG = [];
scaleprob = [];
consecutive = [];
display('in idimprob -- CumG does not have the expected number of columns');
else
idim = -1*ones(m,1);
firstscaleindex = -1*ones(m,1);
scales = zeros(m,q);
idimG = -1*ones(m,q);
mxG = -1*ones(m,q);
scaleprob = -1*ones(m,1);
consecutive = -1*ones(m,1);
for j = 1:q
ind = groupdim*(j-1) + [1:groupdim];
C = CumG(:,ind);
D = C >= t;
%find first index in each row where C >= t
[mx,ind] = max(D,[],2);
for i = 1:m
if mx(i) == 1
idimG(i,j) = ind(i,1);
mxG(i,j) = C(i,ind(i));
elseif mx(i) == 0
idimG(i,j) = -1;
mxG(i,j) = -1;
end
end
%col = mxG(:,j)
end
end
%The intrinsic dimension for a point is the minimum of the intrinsic dimensions for
%each scale for which the intrinsic dimension is computed.
%If it is not computed at any scale idim = -1.
for i = 1:m
ind1 = find(indG(i,:) == 1);
if length(ind1) > 0
idim(i,1) = min(idimG(i,ind1));
indscales = find(idimG(i,:) == idim(i,1));
scales(i,indscales) = 1;
scaleprob(i,1) = length(indscales)/length(ind1);
if indscales == indscales(1) - 1 + [1:length(indscales)]
consecutive(i,1) = 1;
end
firstscaleindex(i,1) = indscales(1);
end
end
end
|
github
|
MelWe/mm-hypothesis-master
|
idimprob2.m
|
.m
|
mm-hypothesis-master/code/vidim2code/idimprob2.m
| 2,395 |
utf_8
|
7cc95d6059d6370a0a744fcb71ce9bd5
|
function [idimsig, idimsigstats] = idimprob2( CumG,q,groupdim,t,indG,ballcount)
%CumG is a matrix whose rows are q groups of cumulative distributions
%of size groupdim
%t is a threshhold 0 <= t <= 1
%The function returns column index of the first element in each row
%which is >= t; if no such index exists, the function returns -1.
[m,n] = size(CumG);
if ~(n == q*groupdim)
idimsig = [];
firstscaleindex = [];
scales = [];
idimG = [];
mxG = [];
scaleprob = [];
consecutive = [];
display('in idimprob -- CumG does not have the expected number of columns');
else
idimsig = -1*ones(m,1);
firstscaleindex = -1*ones(m,1);
scales = zeros(m,q);
idimG = -1*ones(m,q);
mxG = -1*ones(m,q);
scaleprob = -1*ones(m,1);
consecutive = -1*ones(m,1);
for j = 1:q
ind = groupdim*(j-1) + [1:groupdim];
C = CumG(:,ind);
D = C >= t;
%find first index in each row where C >= t
[mx,ind] = max(D,[],2);
for i = 1:m
if mx(i) == 1
idimG(i,j) = ind(i,1);
mxG(i,j) = C(i,ind(i));
elseif mx(i) == 0
idimG(i,j) = -1;
mxG(i,j) = -1;
end
end
%col = mxG(:,j)
end
end
[ idimGsig,scalessig,totalsigscales ] = significantidim(idimG,ballcount );
%The intrinsic dimension for a point is the minimum of the intrinsic dimensions for
%each scale for which the intrinsic dimension is computed.
%If it is not computed at any scale idim = -1.
for i = 1:m
%ind1 = find(indG(i,:) == 1);
ind1 = find(idimGsig(i,:)) > 0;
if length(ind1) > 0
idimsig(i,1) = min(idimGsig(i,ind1));
indscales = find(idimGsig(i,:) == idimsig(i,1));
scales(i,indscales) = 1;
scaleprob(i,1) = length(indscales)/length(ind1);
if indscales == indscales(1) - 1 + [1:length(indscales)]
consecutive(i,1) = 1;
end
firstscaleindex(i,1) = indscales(1);
end
end
totalidimscales = sum(scales,2);
idimsigstats(1).idimsig = idimsig;
idimsigstats(1).firstscaleindex = firstscaleindex;
idimsigstats(1).indG = indG;
idimsigstats(1).scales = scales;
idimsigstats(1).idimG = idimG;
idimsigstats(1).scaleprob = scaleprob;
idimsigstats(1).scales = scales;
idimsigstats(1).consecutive = consecutive;
idimsigstats(1).dense = dense;
idimsigstats(1).SG = SG;
end
|
github
|
MelWe/mm-hypothesis-master
|
testvariancebaseddimLIDAR.m
|
.m
|
mm-hypothesis-master/code/vidimcode/testvariancebaseddimLIDAR.m
| 21,008 |
utf_8
|
134fa64fe2c0f09fad7d1c4fca69bd79
|
function testvariancebaseddimLIDAR( testid )
%This file illustrates the variance based intrinsic dimension code and
%total variance functions on the Bridge_87K.txt file
if testid == 8
fnamedata = '/Users/lindaness/Documents/MATLAB/LIDAR2/Bridge_87K.txt';
data = dlmread(fnamedata);
x = data(:,1);
y = data(:,2);
z = data(:,3);
xdiam = max(x) - min(x);
ydiam = max(y) - min(y);
zdiam = max(z) - min(z);
maxdiam = sqrt(xdiam^2 + ydiam^2 + zdiam^2)
h1 = figure;
scatter3(x,y,z);
str = sprintf('scatterplot of data for testid %d',testid);
title(str)
dirname = '/Users/lindaness/Documents/MATLAB/MSVDLinda/testsLIDAR/';
fnamescatter = [dirname,sprintf('test%d',testid)];
saveas(h1,[fnamescatter,'.fig']);
saveas(h1,[fnamescatter,'.png']);
varthreshhold = .95; K = 3; epszero = 10^(-12); TVfigs = 1;
radii = (maxdiam)*2.^(-1.*[4:7])
q = length(radii);
fname = [dirname,sprintf('testvarbasedidim testid %d',testid)];
idimfigs = 1;
[ idimsummary,istatssummary,idim,firstscaleindex,scaleprob, scales,consecutive,dense,SG,indG,SSVs] = variancebaseddim( data,radii,K,varthreshhold,epszero,idimfigs,fname );
idimsummary
display('columheadings: idim,firstscaleindex, count');
istatssummary
save(fname,'varthreshhold', 'K', 'radii', 'epszero', 'TVfigs', 'fname');
save(fname,'data','-append');
save(fname, 'idimsummary','istatssummary','idim','firstscaleindex','scaleprob', 'scales','consecutive','dense','SG','indG','SSVs','-append');
[SSVEnergy,idimSSVEnergy,EidimSSVEnergy,TV,ETV,idimTV,EidimTV ] = TotalVarianceFunctions(data,idim,SG,radii,q,scales,indG,TVfigs,fname);
save(fname,'SSVEnergy','idimSSVEnergy','EidimSSVEnergy','TV','ETV','idimTV','EidimTV','-append');
elseif testid == 9
fnamedata = '/Users/lindaness/Documents/MATLAB/wisdmreproducibility/datasets/Bridge_87K.txt';
dirname = '/Users/lindaness/Documents/MATLAB/wisdmreproducibility/results/';
fnamescatter = [dirname,sprintf('test%d-data',testid)];
fname = [dirname,sprintf('test%d-results',testid)];
data = dlmread(fnamedata);
x = data(:,1);
y = data(:,2);
z = data(:,3);
xdiam = max(x) - min(x);
ydiam = max(y) - min(y);
zdiam = max(z) - min(z);
maxdiam = sqrt(xdiam^2 + ydiam^2 + zdiam^2)
h1 = figure;
scatter3(x,y,z);
str = sprintf('scatterplot of data for testid %d',testid);
title(str)
saveas(h1,[fnamescatter,'.fig']);
saveas(h1,[fnamescatter,'.png']);
varthreshhold = .95; K = 3; epszero = 10^(-12); TVfigs = 1;
radii = (maxdiam)*2.^(-1.*[4:7])
q = length(radii);
idimfigs = 1;
[ idimsummary,istatssummary,idim,firstscaleindex,scaleprob, scales,consecutive,dense,SG,indG,SSVs] = variancebaseddim( data,radii,K,varthreshhold,epszero,idimfigs,fname );
idimsummary
display('columheadings: idim,firstscaleindex, count');
istatssummary
save(fname,'varthreshhold', 'K', 'radii', 'epszero', 'TVfigs', 'fname');
save(fname,'data','-append');
save(fname, 'idimsummary','istatssummary','idim','firstscaleindex','scaleprob', 'scales','consecutive','dense','SG','indG','SSVs','-append');
[SSVEnergy,idimSSVEnergy,EidimSSVEnergy,TV,ETV,idimTV,EidimTV ] = TotalVarianceFunctions(data,idim,SG,radii,q,scales,indG,TVfigs,fname);
save(fname,'SSVEnergy','idimSSVEnergy','EidimSSVEnergy','TV','ETV','idimTV','EidimTV','-append');
elseif testid == 10
fnamedata = '/Users/lindaness/Documents/MATLAB/wisdmreproducibility/datasets/Bridge_87K.txt';
dirname = '/Users/lindaness/Documents/MATLAB/wisdmreproducibility/results/';
fnamescatter = [dirname,sprintf('test%d-data',testid)];
fname = [dirname,sprintf('test%d-vidim-',testid)];
data = dlmread(fnamedata);
x = data(:,1);
y = data(:,2);
z = data(:,3);
xdiam = max(x) - min(x);
ydiam = max(y) - min(y);
zdiam = max(z) - min(z);
maxdiam = sqrt(xdiam^2 + ydiam^2 + zdiam^2)
h1 = figure;
scatter3(x,y,z);
str = sprintf('scatterplot of data for testid %d',testid);
title(str)
saveas(h1,[fnamescatter,'.fig']);
saveas(h1,[fnamescatter,'.png']);
varthreshhold = .95; K = 3; epszero = 10^(-12); TVfigs = 1;
radii = (maxdiam)*2.^(-1.*[4:7])
q = length(radii)
idimfigs = 1;
[ idimsummary,istatssummary,idim,firstscaleindex,scaleprob, scales,consecutive,dense,SG,indG,SSVs] = variancebaseddim( data,radii,K,varthreshhold,epszero,idimfigs,fname );
idimsummary
display('columheadings: idim,firstscaleindex, count');
istatssummary
save(fname,'varthreshhold', 'K', 'radii', 'epszero', 'TVfigs', 'fname');
save(fname,'data','-append');
save(fname, 'idimsummary','istatssummary','idim','firstscaleindex','scaleprob', 'scales','consecutive','dense','SG','indG','SSVs','-append');
[SSVEnergy,idimSSVEnergy,EidimSSVEnergy,TV,ETV,idimTV,EidimTV ] = TotalVarianceFunctions(data,idim,SG,radii,q,scales,indG,TVfigs,fname);
save(fname,'SSVEnergy','idimSSVEnergy','EidimSSVEnergy','TV','ETV','idimTV','EidimTV','-append');
end
end
function [ idimsummary,istatssummary,idim,firstscaleindex,scaleprob, scales,consecutive,dense,SG,indG,SSVs] = variancebaseddim( data,radii,K,varthreshhold,epszero,idimfigs,fname )
%idim plots are shown if idimfigs == 1
%variance function pots are shown if TVfigs == 1
%radii is a decreasing sequence of radiuses determining a sequence of
%balls around each point. The index of each radius is referred to as the
%scale.
[m,n] = size(data); % m data points, n coordinates
maxdim = min(m,n);
q = length(radii);
%This program looks for points with intrinsic dimensions <= K (with respect
%to the family of point neighborhoods specified by radii
cutoff = K*log(K);
%This function computes the intrinsic dimension idim for each point by
%a concentration of variance analysis using varthreshhold (e.g. .95)
%SSVs is an m x maxdim*q matrix of q groups of squared singular values
%of matrices of points in each ball, the matrices are centered so EV = 0
%The squared singular values are then the variances of each centered coordinate.
%PeG is an m x maxdim*q matrix of q groups of discrete probability distriutions
%for each of the m points (relative variances); SG is an m x q matrix of
%total variances for each ball; CumG is an m x maxdim*q matrix of q groups
%of vectors (c1, ..., cn) defining the cumulative distribution for
%(p1,..,pn) so cj = p1 + ... pj
% idim(p) = i, i = minimum over the scales of smallestindex j cj >= varthresshold
%e.g if varthreshhold = .95 ,idim(p) = i if there is a ball (scale) for which
%the sum of the variances of the first i centered coordinates >= .95
%scales is an m xq matrix of 0's and 1's. each row (pt) has 1's at the scales
%i, such that ci >= varthresshold and i = idim(pt)
%i.e. idim is computed by concentration of variance analysis and the
%scales is the set of indices of balls where the variance accumulates to
%the fastest to varthreshhold
%Two summary matrices are computed: idimsummary and istatssummary
%rows of idimsummary (idim value, number of points with idim value)
%i.e. the discrete distribution of idim for the data set
%rows of istats summary (idim value, first scale index, number of points
%with the specified idim value and first scale index.
%i.e. the discrete distribution of idim,firstscale for the data set
%If idimfigs == 1 scatter plots of the data points color-coded by idim
%are computed
%Different Total Variance functions are computed for each point, including
%the SSVEnergy function.
%Summaries of idim statistics are computed; idim and the Total Varianc
%functions are plotted
[ SSVs,dense,ballcount ] = ComputeSSVs( data,radii,cutoff );
M = SSVs;
[ PrG,SG,CumG,indG ] = ProbDistGroups(M,q,maxdim,dense,epszero);
%PrG1599 = PrG(1599,:)
%SG199 = SG(1599,:)
%CumG1599 = CumG(1599,:)
groupdim = n;
t = varthreshhold;
[idim,firstscaleindex, scales,idimG,mxG,scaleprob,consecutive] = idimprob( CumG,q,groupdim,t,indG);
u = unique(idim);
idimsummary = zeros(length(u),2 );
for i = 1:length(u)
ind = find(idim == u(i));
lgth = length(ind);
idimsummary(i,:) = [u(i),lgth];
end
[istats,irhs,ilhs] = unique([idim,firstscaleindex],'rows');
%istatssummary = zeros(length(istats),4);
istatssummary = zeros(length(istats),3);
for i = 1:size(istats,1)
%x = abs(istats(i,1:3));
x = istats(i,1:2);
y = length(find(ilhs == i));
istatssummary(i,:) = [x,y];
end
if idimfigs == 1
ind = find(idim > 0);
m2 = length(ind);
h = figure;
a = [1:m2];
b = idim(ind,:);
scatter(a,b,100);
titlestr = sprintf('ordered points with y coordinate = idim');
if ~length(fname) == 0
fname1 = [fname,'orderedidim','.png'];
saveas(h,fname1);
fname1 = [fname,'orderedidim','.fig'];
saveas(h,fname1);
end
if n == 3
X = data(ind,1); Y = data(ind,2); Z = data(ind,3);
idim2 = idim(ind,:);
firstscaleindex2 = firstscaleindex(ind,:);
h = figure;
colormap(jet(m2));
scatter3(X,Y,Z,10,idim2);
titlestr = sprintf('points color-coded by idim');
title(titlestr);
if ~length(fname) == 0
fname1 = [fname,'idim','.png'];
saveas(h,fname1);
fname1 = [fname,'idim','.fig'];
saveas(h,fname1);
end
h = figure;
colormap(jet(m));
scatter3(X,Y,Z,10,ilhs(ind,:));
%scatter3(X,Y,Z,100,firstscaleindex2);
titlestr = sprintf('points color-coded by lexicographic ordering of idim,firstscaleindex');
title(titlestr);
if ~length(fname) == 0
fname1 = [fname,'lexidim','.png'];
saveas(h,fname1);
fname1 = [fname,'lexidim','.fig'];
saveas(h,fname1);
end
end
end
end
function [SSVEnergy,idimSSVEnergy,EidimSSVEnergy,TV,ETV,idimTV,EidimTV ] = TotalVarianceFunctions(data,idim, SG,radii,q,scales,indG,TVfigs,fname)
%data is an m xn matrix of m data points with n coordinate
%SG is an m x q matrix of total variances for data in each of the q balls
%with radii specified in radius (total variances of the centered data)
%SG entries for a ball are -1 if the intrinsic dimension was not computed for that ball
%due to too few points etc
%scales is an m x q matrix of 0's and 1's specifying the scales at which idim was observed
%for each data point
%indG is an m x q matrix of 0's and 1's specifying the scales for which
%intrinsic dimension was computed
%A variety of total variance functions are computed including the SSVEnergy
%function we computed at WiSDM
%if TVfig == 1, the total variance functions are plotted for the subset of
%points for which intrinsic dimension was computed.
[m,n] = size(data);
%SG is an m x q matrix containg the total variances for each ball
%(or -1's for the ball where SG and hence the intrinsic dimension were
%not computed
%Compute different Versions of Total Variance Functions
%TV sum of total variances over the relevant balls
TV = sum(SG.*indG,2);
ETV = TV./sum(indG,2); %m x 1 average of total variances of relevant balls
idimTV = sum(scales.*SG,2); %sum of scale variances for idim scales
%total variance for each of these scale is concentrated near idim scales
EidimTV = idimTV./sum(scales,2); %Expected Value over the scales where
%local idim = idim for the point
R = repmat(radii.^2,m,1);
RelSG = SG./R; %RelSG total variances for each ball are normalized by
%dividing by the square of the radius; functions analagous to above are
%computed from the relative variances.
SSVEnergy =sum(RelSG,2) ; %This is the SSVEnergy function computed at WiSDM
idimSSVEnergy = sum(scales.*RelSG,2);
EidimSSVEnergy = idimSSVEnergy./sum(scales,2);
if TVfigs == 1
ind = find(idim > 0);
SG = SG(ind,:);
m = size(data(ind,:),1);
%h = figure;
%x = 1:m;
%hold on
%for i = 1:q
%plot(x,SG(:,i));
%end
%titlestr = sprintf('Total Variance Curves for each scale');
%title(titlestr)
%hold off
if n == 3
X = data(ind,1); Y = data(ind,2); Z = data(ind,3);
TV = TV(ind,:);
idimTV = idimTV(ind,:);
EidimTV = EidimTV(ind,:);
SSVEnergy = SSVEnergy(ind,:);
idimSSVEnergy = idimSSVEnergy(ind,:);
EidimSSVEnergy = EidimSSVEnergy(ind,:);
h = figure;
colormap(jet(length(ind)));
scatter3(X,Y,Z,100,TV);
titlestr = sprintf('points color-coded by sum of Total Variances over scales where idim was computed');
title(titlestr);
if ~length(fname) == 0
fname1 = [fname,'TV','.png'];
saveas(h,fname1);
fname1 = [fname,'TV','.fig'];
saveas(h,fname1);
end
h = figure;
colormap(jet(length(ind)));
scatter3(X,Y,Z,100,idimTV);
titlestr = sprintf('points color-coded by sum of Total Variance over idim scales for each point') ;
title(titlestr);
if ~length(fname) == 0
fname1 = [fname,'idimTV','.png'];
saveas(h,fname1);
fname1 = [fname,'idimTV','.fig'];
saveas(h,fname1);
end
h = figure;
colormap(jet(length(ind)));
scatter3(X,Y,Z,100,EidimTV);
titlestr = sprintf('points color-coded by EV of Total Variance over idim scales for each point') ;
title(titlestr);
if ~length(fname) == 0
fname1 = [fname,'EidimTV','.png'];
saveas(h,fname1);
fname1 = [fname,'EidimTV','.fig'];
saveas(h,fname1);
end
h = figure;
colormap(jet(length(ind)));
scatter3(X,Y,Z,100,SSVEnergy);
titlestr = sprintf('SSVEnergy - points color-coded by sum of normalized total variances over scales where idim was computed') ;
title(titlestr);
if ~length(fname) == 0
fname1 = [fname,'SSVEnergy','.png'];
saveas(h,fname1);
fname1 = [fname,'SSVEnergy','.fig'];
saveas(h,fname1);
end
h = figure;
colormap(jet(length(ind)));
scatter3(X,Y,Z,100,idimSSVEnergy);
titlestr = sprintf('idmSSVEnergy - points color-coded by sum of normalized total variances over idim scales') ;
title(titlestr);
if ~length(fname) == 0
fname1 = [fname,'idimSSVEnergy','.png'];
saveas(h,fname1);
fname1 = [fname,'idimSSVEnergy','.fig'];
saveas(h,fname1);
end
h = figure;
colormap(jet(length(ind)));
scatter3(X,Y,Z,100,EidimSSVEnergy);
titlestr = sprintf('EidmSSVEnergy - points color-coded by EV of normalized total variances over idim scales') ;
title(titlestr);
if ~length(fname) == 0
fname1 = [fname,'EidimSSVEnergy','.png'];
saveas(h,fname1);
fname1 = [fname,'EidimSSVEnergy','.fig'];
saveas(h,fname1);
end
end
end
end
function [ SSVs,dense,ballcount ] = ComputeSSVs( data,radii,cutoff )
% data is an m x n matrix, whose rows are the data
%r is a 1 x q list of decreasing radii (e.g 2^0, 2^(-1), 2^(-2), ....);
%This function computes the squared singular values for each point p and each
%subset d(p,r) of data points at distance <= r from data point p
%Results are returned in the m x q*maxdim matrix SSVs, maxdim = min(m,n);
%For the ith data point p = data(i,:)
%SSVs for p and d(p,r(j)) are in row i, columns [1:maxdim] + maxdim*(j-1)
%SSVs are not computed if |d(p,r)| < cutoff, instead -1's are stored in SSVs \
%dense is an m x q matrix of 0's and 1's
%dense(i,j) = |d(p,r(j))| < cutoff
[m,n] = size(data);
q = length(radii);
%maxdim is the maximum number of non-zero singular values
maxdim = min(m,n);
%dense(i,j) = 1 if |d(p,r)| > cutoff else 0, p = data(i,:)
dense = ones(m,q);
SSVs = -1*ones(m,q*maxdim);
ballcount = zeros(m,q);
%for each point
for i = 1:m
if mod(i,1000) == 0
i
end
p = data(i,:);
ballmembership = zeros(m,q);
for j = 1:q
r = radii(j);
[b,B] = ball(data,p,r);
ballmembership(:,j) = B;
%compute EV of b and translate by -EV so EV(c) = 0;
c = center(b);
cardc = size(c,1);
if cardc > cutoff
s = svd(c);
sq = s.*s;
inds2 = [1:maxdim] + maxdim*(j-1);
SSVs(i,inds2) = sq;
else
dense(i,j) = 0;
end
end
ballcount(i,:) = sum(ballmembership);
end
end
function [v,B] = ball( data,p,r)
%% p=center; r=radius %%
%This functions finds the data points in the ball of radius r
%centered at p.
[m,n] = size(data);
x = sqrt(sum((data- ones(m,1)*p).^2,2));
B= x < r*ones(m,1);
v=data(B,:);
end
function [ centereddata ] = center( data )
%UNTITLED4 Summary of this function goes here
% Detailed explanation goes here
[m,n] = size(data);
EV = (1/m)*sum(data);
centereddata = data - ones(m,1)*EV;
end
function [ PrG,SG,CumG,indG ] = ProbDistGroups(M,q,maxdim,dense,epszero)
%M is an m x q*maxdim matrix
%dense is an m x q matrix
%epszero very small and positive and used to test for zero e.g 10^(-12)
%SG is m x q; PrG and SG are m x q*maxdim; indG is m x q
%For the jth group of maxdim columns, for each row i, if dense(i,j) == 1 and
%if the entries are >=0 with positive sum (> epszero) , indG(i,j) = 1 and
%the rowsum,probability distribution, and cumlative probability distribution
%of the row are computed and stored in the matrices SG, PrG and CumG.
%for the other rows in the group indG = 0 and the entries of
%SG, PrG and CumG are -1's.
%if M does not have q*maxdim columns PrG,SG,CumG have -1 entries and inG = 0
[m,n] = size(M);
PrG = -1*ones(m,n);
CumG = -1*ones(m,n);
SG = -1*ones(m,q);
indG = zeros(m,q);
if n == q*maxdim
for j = 1:q
inddense = find(dense(:,j) == 1);
indj = [1:maxdim] + maxdim*(j-1);
[ Pr,S,Cum,ind ] = Probdist(M(inddense,indj),epszero);
PrG(inddense,indj) = Pr;
SG(inddense,j) = S;
CumG(inddense,indj) = Cum;
indG(inddense(ind),j) = 1;
end
end
end
function [ Pr,S,Cum,ind ] = Probdist(M,epszero)
%M is a m x n matrix
%S is an m x 1 matrix; Cum and Pr are m x n matrices.
%S,Cum,Pr are initialized to -1;
%for the rows of M which are non-negative with positive sum (> epszero)
%S is the sum of the row
%Pr is the discrete probability distribution determined by the row
%Cum is the cumulative distribution determined by the row
%Example row = [1,2,3]; S = 6, Pr = [1/6,2/6,3/6], Cum = [1/6,1/2,1]
%For the other rows of M, the entries of S, Pr, and Cu are -1.
%ind is the index of the non-negative rows with positive sum
[m,n] = size(M);
S = -1*ones(m,1);
Pr = -1*ones(m,n);
Cum = -1*ones(m,n);
nonneg = M >= 0;
possum = sum(M,2);
N = sum(nonneg,2);
ind = find(N == n & possum > epszero);
S(ind,:) = sum(M(ind,:),2);
k = length(ind);
if k > 0
Tmp = zeros(k,1);
for i = 1:n
Pr(ind,i) = M(ind,i)./S(ind,1);
Tmp = Tmp + Pr(ind,i);
Cum(ind,i) = Tmp;
end
end
end
function [idim,firstscaleindex, scales,idimG,mxG,scaleprob,consecutive] = idimprob( CumG,q,groupdim,t,indG)
%CumG is a matrix whose rows are q groups of cumulative distributions
%of size groupdim
%t is a threshhold 0 <= t <= 1
%The function returns column index of the first element in each row
%which is >= t; if no such index exists, the function returns -1.
[m,n] = size(CumG);
if ~(n == q*groupdim)
idim = [];
firstscaleindex = [];
scales = [];
idimG = [];
mxG = [];
scaleprob = [];
consecutive = [];
display('in idimprob -- CumG does not have the expected number of columns');
else
idim = -1*ones(m,1);
firstscaleindex = -1*ones(m,1);
scales = zeros(m,q);
idimG = -1*ones(m,q);
mxG = -1*ones(m,q);
scaleprob = -1*ones(m,1);
consecutive = -1*ones(m,1);
for j = 1:q
ind = groupdim*(j-1) + [1:groupdim];
C = CumG(:,ind);
D = C >= t;
%find first index in each row where C >= t
[mx,ind] = max(D,[],2);
for i = 1:m
if mx(i) == 1
idimG(i,j) = ind(i,1);
mxG(i,j) = C(i,ind(i));
elseif mx(i) == 0
idimG(i,j) = -1;
mxG(i,j) = -1;
end
end
%col = mxG(:,j)
end
end
%The intrinsic dimension for a point is the minimum of the intrinsic dimensions for
%each scale for which the intrinsic dimension is computed.
%If it is not computed at any scale idim = -1.
for i = 1:m
ind1 = find(indG(i,:) == 1);
if length(ind1) > 0
idim(i,1) = min(idimG(i,ind1));
indscales = find(idimG(i,:) == idim(i,1));
scales(i,indscales) = 1;
scaleprob(i,1) = length(indscales)/length(ind1);
if indscales == indscales(1) - 1 + [1:length(indscales)]
consecutive(i,1) = 1;
end
firstscaleindex(i,1) = indscales(1);
end
end
end
|
github
|
MelWe/mm-hypothesis-master
|
computevidim.m
|
.m
|
mm-hypothesis-master/code/vidimcode/computevidim.m
| 16,974 |
utf_8
|
305cfbbbc17b00669d077b04063972bf
|
function [data,idim] = computevidim( data,radii,K,varthreshhold,epszero,idimfigs,TVfigs, fname)
%This computes variance-based intrinsic dimension for the
%m x n data matrix. (The rows are the data points.)
%Two summaries idimsummary and istatssummary are displayed (and saved).
%The results are saved in the file [dirname,fname,'-vidim-']
[ idimsummary,istatssummary,idim,firstscaleindex,scaleprob, scales,consecutive,dense,SG,indG,SSVs] = variancebaseddim( data,radii,K,varthreshhold,epszero,idimfigs,fname );
idimsummary
display('columheadings: idim,firstscaleindex, count');
istatssummary
save(fname,'varthreshhold', 'K', 'radii', 'epszero', 'TVfigs', 'fname');
save(fname,'data','-append');
save(fname, 'idimsummary','istatssummary','idim','firstscaleindex','scaleprob', 'scales','consecutive','dense','SG','indG','SSVs','-append');
q = length(radii);
[SSVEnergy,idimSSVEnergy,EidimSSVEnergy,TV,ETV,idimTV,EidimTV ] = TotalVarianceFunctions(data,idim,SG,radii,q,scales,indG,TVfigs,fname);
save(fname,'SSVEnergy','idimSSVEnergy','EidimSSVEnergy','TV','ETV','idimTV','EidimTV','-append');
end
function [ idimsummary,istatssummary,idim,firstscaleindex,scaleprob, scales,consecutive,dense,SG,indG,SSVs] = variancebaseddim( data,radii,K,varthreshhold,epszero,idimfigs,fname )
%idim plots are shown if idimfigs == 1
%variance function pots are shown if TVfigs == 1
%radii is a decreasing sequence of radiuses determining a sequence of
%balls around each point. The index of each radius is referred to as the
%scale.
[m,n] = size(data); % m data points, n coordinates
maxdim = min(m,n);
q = length(radii);
%This program looks for points with intrinsic dimensions <= K (with respect
%to the family of point neighborhoods specified by radii
cutoff = K*log(K);
%This function computes the intrinsic dimension idim for each point by
%a concentration of variance analysis using varthreshhold (e.g. .95)
%SSVs is an m x maxdim*q matrix of q groups of squared singular values
%of matrices of points in each ball, the matrices are centered so EV = 0
%The squared singular values are then the variances of each centered coordinate.
%PeG is an m x maxdim*q matrix of q groups of discrete probability distriutions
%for each of the m points (relative variances); SG is an m x q matrix of
%total variances for each ball; CumG is an m x maxdim*q matrix of q groups
%of vectors (c1, ..., cn) defining the cumulative distribution for
%(p1,..,pn) so cj = p1 + ... pj
% idim(p) = i, i = minimum over the scales of smallestindex j cj >= varthresshold
%e.g if varthreshhold = .95 ,idim(p) = i if there is a ball (scale) for which
%the sum of the variances of the first i centered coordinates >= .95
%scales is an m xq matrix of 0's and 1's. each row (pt) has 1's at the scales
%i, such that ci >= varthresshold and i = idim(pt)
%i.e. idim is computed by concentration of variance analysis and the
%scales is the set of indices of balls where the variance accumulates to
%the fastest to varthreshhold
%Two summary matrices are computed: idimsummary and istatssummary
%rows of idimsummary (idim value, number of points with idim value)
%i.e. the discrete distribution of idim for the data set
%rows of istats summary (idim value, first scale index, number of points
%with the specified idim value and first scale index.
%i.e. the discrete distribution of idim,firstscale for the data set
%If idimfigs == 1 scatter plots of the data points color-coded by idim
%are computed
%Different Total Variance functions are computed for each point, including
%the SSVEnergy function.
%Summaries of idim statistics are computed; idim and the Total Varianc
%functions are plotted
[ SSVs,dense,ballcount ] = ComputeSSVs( data,radii,cutoff );
M = SSVs;
[ PrG,SG,CumG,indG ] = ProbDistGroups(M,q,maxdim,dense,epszero);
%PrG1599 = PrG(1599,:)
%SG199 = SG(1599,:)
%CumG1599 = CumG(1599,:)
groupdim = n;
t = varthreshhold;
[idim,firstscaleindex, scales,idimG,mxG,scaleprob,consecutive] = idimprob( CumG,q,groupdim,t,indG);
u = unique(idim);
idimsummary = zeros(length(u),2 );
for i = 1:length(u)
ind = find(idim == u(i));
lgth = length(ind);
idimsummary(i,:) = [u(i),lgth];
end
[istats,irhs,ilhs] = unique([idim,firstscaleindex],'rows');
%istatssummary = zeros(length(istats),4);
istatssummary = zeros(length(istats),3);
for i = 1:size(istats,1)
%x = abs(istats(i,1:3));
x = istats(i,1:2);
y = length(find(ilhs == i));
istatssummary(i,:) = [x,y];
end
if idimfigs == 1
ind = find(idim > 0);
m2 = length(ind);
h = figure;
a = [1:m2];
b = idim(ind,:);
scatter(a,b,100);
titlestr = sprintf('ordered points with y coordinate = idim');
if ~length(fname) == 0
fname1 = [fname,'orderedidim','.png'];
saveas(h,fname1);
fname1 = [fname,'orderedidim','.fig'];
saveas(h,fname1);
end
if n == 3
X = data(ind,1); Y = data(ind,2); Z = data(ind,3);
idim2 = idim(ind,:);
firstscaleindex2 = firstscaleindex(ind,:);
h = figure;
colormap(jet(m2));
scatter3(X,Y,Z,10,idim2);
titlestr = sprintf('points color-coded by idim');
title(titlestr);
if ~length(fname) == 0
fname1 = [fname,'idim','.png'];
saveas(h,fname1);
fname1 = [fname,'idim','.fig'];
saveas(h,fname1);
end
h = figure;
colormap(jet(m));
scatter3(X,Y,Z,10,ilhs(ind,:));
%scatter3(X,Y,Z,100,firstscaleindex2);
titlestr = sprintf('points color-coded by lexicographic ordering of idim,firstscaleindex');
title(titlestr);
if ~length(fname) == 0
fname1 = [fname,'lexidim','.png'];
saveas(h,fname1);
fname1 = [fname,'lexidim','.fig'];
saveas(h,fname1);
end
end
end
end
function [SSVEnergy,idimSSVEnergy,EidimSSVEnergy,TV,ETV,idimTV,EidimTV ] = TotalVarianceFunctions(data,idim, SG,radii,q,scales,indG,TVfigs,fname)
%data is an m xn matrix of m data points with n coordinate
%SG is an m x q matrix of total variances for data in each of the q balls
%with radii specified in radius (total variances of the centered data)
%SG entries for a ball are -1 if the intrinsic dimension was not computed for that ball
%due to too few points etc
%scales is an m x q matrix of 0's and 1's specifying the scales at which idim was observed
%for each data point
%indG is an m x q matrix of 0's and 1's specifying the scales for which
%intrinsic dimension was computed
%A variety of total variance functions are computed including the SSVEnergy
%function we computed at WiSDM
%if TVfig == 1, the total variance functions are plotted for the subset of
%points for which intrinsic dimension was computed.
[m,n] = size(data);
%SG is an m x q matrix containg the total variances for each ball
%(or -1's for the ball where SG and hence the intrinsic dimension were
%not computed
%Compute different Versions of Total Variance Functions
%TV sum of total variances over the relevant balls
TV = sum(SG.*indG,2);
ETV = TV./sum(indG,2); %m x 1 average of total variances of relevant balls
idimTV = sum(scales.*SG,2); %sum of scale variances for idim scales
%total variance for each of these scale is concentrated near idim scales
EidimTV = idimTV./sum(scales,2); %Expected Value over the scales where
%local idim = idim for the point
R = repmat(radii.^2,m,1);
RelSG = SG./R; %RelSG total variances for each ball are normalized by
%dividing by the square of the radius; functions analagous to above are
%computed from the relative variances.
SSVEnergy =sum(RelSG,2) ; %This is the SSVEnergy function computed at WiSDM
idimSSVEnergy = sum(scales.*RelSG,2);
EidimSSVEnergy = idimSSVEnergy./sum(scales,2);
if TVfigs == 1
ind = find(idim > 0);
SG = SG(ind,:);
m = size(data(ind,:),1);
%h = figure;
%x = 1:m;
%hold on
%for i = 1:q
%plot(x,SG(:,i));
%end
%titlestr = sprintf('Total Variance Curves for each scale');
%title(titlestr)
%hold off
if n == 3
X = data(ind,1); Y = data(ind,2); Z = data(ind,3);
TV = TV(ind,:);
idimTV = idimTV(ind,:);
EidimTV = EidimTV(ind,:);
SSVEnergy = SSVEnergy(ind,:);
idimSSVEnergy = idimSSVEnergy(ind,:);
EidimSSVEnergy = EidimSSVEnergy(ind,:);
h = figure;
colormap(jet(length(ind)));
scatter3(X,Y,Z,100,TV);
titlestr = sprintf('points color-coded by sum of Total Variances over scales where idim was computed');
title(titlestr);
if ~length(fname) == 0
fname1 = [fname,'TV','.png'];
saveas(h,fname1);
fname1 = [fname,'TV','.fig'];
saveas(h,fname1);
end
h = figure;
colormap(jet(length(ind)));
scatter3(X,Y,Z,100,idimTV);
titlestr = sprintf('points color-coded by sum of Total Variance over idim scales for each point') ;
title(titlestr);
if ~length(fname) == 0
fname1 = [fname,'idimTV','.png'];
saveas(h,fname1);
fname1 = [fname,'idimTV','.fig'];
saveas(h,fname1);
end
h = figure;
colormap(jet(length(ind)));
scatter3(X,Y,Z,100,EidimTV);
titlestr = sprintf('points color-coded by EV of Total Variance over idim scales for each point') ;
title(titlestr);
if ~length(fname) == 0
fname1 = [fname,'EidimTV','.png'];
saveas(h,fname1);
fname1 = [fname,'EidimTV','.fig'];
saveas(h,fname1);
end
h = figure;
colormap(jet(length(ind)));
scatter3(X,Y,Z,100,SSVEnergy);
titlestr = sprintf('SSVEnergy - points color-coded by sum of normalized total variances over scales where idim was computed') ;
title(titlestr);
if ~length(fname) == 0
fname1 = [fname,'SSVEnergy','.png'];
saveas(h,fname1);
fname1 = [fname,'SSVEnergy','.fig'];
saveas(h,fname1);
end
h = figure;
colormap(jet(length(ind)));
scatter3(X,Y,Z,100,idimSSVEnergy);
titlestr = sprintf('idmSSVEnergy - points color-coded by sum of normalized total variances over idim scales') ;
title(titlestr);
if ~length(fname) == 0
fname1 = [fname,'idimSSVEnergy','.png'];
saveas(h,fname1);
fname1 = [fname,'idimSSVEnergy','.fig'];
saveas(h,fname1);
end
h = figure;
colormap(jet(length(ind)));
scatter3(X,Y,Z,100,EidimSSVEnergy);
titlestr = sprintf('EidmSSVEnergy - points color-coded by EV of normalized total variances over idim scales') ;
title(titlestr);
if ~length(fname) == 0
fname1 = [fname,'EidimSSVEnergy','.png'];
saveas(h,fname1);
fname1 = [fname,'EidimSSVEnergy','.fig'];
saveas(h,fname1);
end
end
end
end
function [ SSVs,dense,ballcount ] = ComputeSSVs( data,radii,cutoff )
% data is an m x n matrix, whose rows are the data
%r is a 1 x q list of decreasing radii (e.g 2^0, 2^(-1), 2^(-2), ....);
%This function computes the squared singular values for each point p and each
%subset d(p,r) of data points at distance <= r from data point p
%Results are returned in the m x q*maxdim matrix SSVs, maxdim = min(m,n);
%For the ith data point p = data(i,:)
%SSVs for p and d(p,r(j)) are in row i, columns [1:maxdim] + maxdim*(j-1)
%SSVs are not computed if |d(p,r)| < cutoff, instead -1's are stored in SSVs \
%dense is an m x q matrix of 0's and 1's
%dense(i,j) = |d(p,r(j))| < cutoff
[m,n] = size(data);
q = length(radii);
%maxdim is the maximum number of non-zero singular values
maxdim = min(m,n);
%dense(i,j) = 1 if |d(p,r)| > cutoff else 0, p = data(i,:)
dense = ones(m,q);
SSVs = -1*ones(m,q*maxdim);
ballcount = zeros(m,q);
%for each point
for i = 1:m
if mod(i,1000) == 0
i
end
p = data(i,:);
ballmembership = zeros(m,q);
for j = 1:q
r = radii(j);
[b,B] = ball(data,p,r);
ballmembership(:,j) = B;
%compute EV of b and translate by -EV so EV(c) = 0;
c = center(b);
cardc = size(c,1);
if cardc > cutoff
s = svd(c);
sq = s.*s;
inds2 = [1:maxdim] + maxdim*(j-1);
SSVs(i,inds2) = sq;
else
dense(i,j) = 0;
end
end
ballcount(i,:) = sum(ballmembership);
end
end
function [v,B] = ball( data,p,r)
%% p=center; r=radius %%
%This functions finds the data points in the ball of radius r
%centered at p.
[m,n] = size(data);
x = sqrt(sum((data- ones(m,1)*p).^2,2));
B= x < r*ones(m,1);
v=data(B,:);
end
function [ centereddata ] = center( data )
%UNTITLED4 Summary of this function goes here
% Detailed explanation goes here
[m,n] = size(data);
EV = (1/m)*sum(data);
centereddata = data - ones(m,1)*EV;
end
function [ PrG,SG,CumG,indG ] = ProbDistGroups(M,q,maxdim,dense,epszero)
%M is an m x q*maxdim matrix
%dense is an m x q matrix
%epszero very small and positive and used to test for zero e.g 10^(-12)
%SG is m x q; PrG and SG are m x q*maxdim; indG is m x q
%For the jth group of maxdim columns, for each row i, if dense(i,j) == 1 and
%if the entries are >=0 with positive sum (> epszero) , indG(i,j) = 1 and
%the rowsum,probability distribution, and cumlative probability distribution
%of the row are computed and stored in the matrices SG, PrG and CumG.
%for the other rows in the group indG = 0 and the entries of
%SG, PrG and CumG are -1's.
%if M does not have q*maxdim columns PrG,SG,CumG have -1 entries and inG = 0
[m,n] = size(M);
PrG = -1*ones(m,n);
CumG = -1*ones(m,n);
SG = -1*ones(m,q);
indG = zeros(m,q);
if n == q*maxdim
for j = 1:q
inddense = find(dense(:,j) == 1);
indj = [1:maxdim] + maxdim*(j-1);
[ Pr,S,Cum,ind ] = Probdist(M(inddense,indj),epszero);
PrG(inddense,indj) = Pr;
SG(inddense,j) = S;
CumG(inddense,indj) = Cum;
indG(inddense(ind),j) = 1;
end
end
end
function [ Pr,S,Cum,ind ] = Probdist(M,epszero)
%M is a m x n matrix
%S is an m x 1 matrix; Cum and Pr are m x n matrices.
%S,Cum,Pr are initialized to -1;
%for the rows of M which are non-negative with positive sum (> epszero)
%S is the sum of the row
%Pr is the discrete probability distribution determined by the row
%Cum is the cumulative distribution determined by the row
%Example row = [1,2,3]; S = 6, Pr = [1/6,2/6,3/6], Cum = [1/6,1/2,1]
%For the other rows of M, the entries of S, Pr, and Cu are -1.
%ind is the index of the non-negative rows with positive sum
[m,n] = size(M);
S = -1*ones(m,1);
Pr = -1*ones(m,n);
Cum = -1*ones(m,n);
nonneg = M >= 0;
possum = sum(M,2);
N = sum(nonneg,2);
ind = find(N == n & possum > epszero);
S(ind,:) = sum(M(ind,:),2);
k = length(ind);
if k > 0
Tmp = zeros(k,1);
for i = 1:n
Pr(ind,i) = M(ind,i)./S(ind,1);
Tmp = Tmp + Pr(ind,i);
Cum(ind,i) = Tmp;
end
end
end
function [idim,firstscaleindex, scales,idimG,mxG,scaleprob,consecutive] = idimprob( CumG,q,groupdim,t,indG)
%CumG is a matrix whose rows are q groups of cumulative distributions
%of size groupdim
%t is a threshhold 0 <= t <= 1
%The function returns column index of the first element in each row
%which is >= t; if no such index exists, the function returns -1.
[m,n] = size(CumG);
if ~(n == q*groupdim)
idim = [];
firstscaleindex = [];
scales = [];
idimG = [];
mxG = [];
scaleprob = [];
consecutive = [];
display('in idimprob -- CumG does not have the expected number of columns');
else
idim = -1*ones(m,1);
firstscaleindex = -1*ones(m,1);
scales = zeros(m,q);
idimG = -1*ones(m,q);
mxG = -1*ones(m,q);
scaleprob = -1*ones(m,1);
consecutive = -1*ones(m,1);
for j = 1:q
ind = groupdim*(j-1) + [1:groupdim];
C = CumG(:,ind);
D = C >= t;
%find first index in each row where C >= t
[mx,ind] = max(D,[],2);
for i = 1:m
if mx(i) == 1
idimG(i,j) = ind(i,1);
mxG(i,j) = C(i,ind(i));
elseif mx(i) == 0
idimG(i,j) = -1;
mxG(i,j) = -1;
end
end
%col = mxG(:,j)
end
end
%The intrinsic dimension for a point is the minimum of the intrinsic dimensions for
%each scale for which the intrinsic dimension is computed.
%If it is not computed at any scale idim = -1.
for i = 1:m
ind1 = find(indG(i,:) == 1);
if length(ind1) > 0
idim(i,1) = min(idimG(i,ind1));
indscales = find(idimG(i,:) == idim(i,1));
scales(i,indscales) = 1;
scaleprob(i,1) = length(indscales)/length(ind1);
if indscales == indscales(1) - 1 + [1:length(indscales)]
consecutive(i,1) = 1;
end
firstscaleindex(i,1) = indscales(1);
end
end
end
|
github
|
MelWe/mm-hypothesis-master
|
idimprob.m
|
.m
|
mm-hypothesis-master/code/vidimunpackedcode/idimprob.m
| 1,907 |
utf_8
|
ad428ae3d0eed13d1868b9a7f0230b9d
|
function [idim,firstscaleindex, scales,idimG,mxG,scaleprob,consecutive] = idimprob( CumG,q,groupdim,t,indG)
%CumG is a matrix whose rows are q groups of cumulative distributions
%of size groupdim
%t is a threshhold 0 <= t <= 1
%The function returns column index of the first element in each row
%which is >= t; if no such index exists, the function returns -1.
[m,n] = size(CumG);
if ~(n == q*groupdim)
idim = [];
firstscaleindex = [];
scales = [];
idimG = [];
mxG = [];
scaleprob = [];
consecutive = [];
display('in idimprob -- CumG does not have the expected number of columns');
else
idim = -1*ones(m,1);
firstscaleindex = -1*ones(m,1);
scales = zeros(m,q);
idimG = -1*ones(m,q);
mxG = -1*ones(m,q);
scaleprob = -1*ones(m,1);
consecutive = -1*ones(m,1);
for j = 1:q
ind = groupdim*(j-1) + [1:groupdim];
C = CumG(:,ind);
D = C >= t;
%find first index in each row where C >= t
[mx,ind] = max(D,[],2);
for i = 1:m
if mx(i) == 1
idimG(i,j) = ind(i,1);
mxG(i,j) = C(i,ind(i));
elseif mx(i) == 0
idimG(i,j) = -1;
mxG(i,j) = -1;
end
end
%col = mxG(:,j)
end
end
%The intrinsic dimension for a point is the minimum of the intrinsic dimensions for
%each scale for which the intrinsic dimension is computed.
%If it is not computed at any scale idim = -1.
for i = 1:m
ind1 = find(indG(i,:) == 1);
if length(ind1) > 0
idim(i,1) = min(idimG(i,ind1));
indscales = find(idimG(i,:) == idim(i,1));
scales(i,indscales) = 1;
scaleprob(i,1) = length(indscales)/length(ind1);
if indscales == indscales(1) - 1 + [1:length(indscales)]
consecutive(i,1) = 1;
end
firstscaleindex(i,1) = indscales(1);
end
end
end
|
github
|
xiaoxiaojiangshang/Programs-master
|
cvx_version.m
|
.m
|
Programs-master/matlab/cvx/cvx_version.m
| 14,459 |
utf_8
|
64d0f08cf9bf3c75fcad41acaf35a8c0
|
function varargout = cvx_version( varargin )
% CVX_VERSION Returns version and environment information for CVX.
%
% When called with no arguments, CVX_VERSION prints out version and
% platform information that is needed when submitting CVX bug reports.
%
% This function is also used internally to return useful variables that
% allows CVX to adjust its settings to the current environment.
global cvx___
args = varargin;
compile = false;
quick = nargout > 0;
if nargin
if ~ischar( args{1} ),
quick = true;
else
tt = strcmp( args, '-quick' );
quick = any( tt );
if quick, args(tt) = []; end
tt = strcmp( args, '-compile' );
compile = any( tt );
if compile, quick = false; args(tt) = []; end
end
end
if isfield( cvx___, 'loaded' ),
if quick, return; end
fs = cvx___.fs;
mpath = cvx___.where;
isoctave = cvx___.isoctave;
else
% Matlab / Octave flag
isoctave = exist( 'OCTAVE_VERSION', 'builtin' );
% File and path separators, MEX extension
if isoctave,
comp = octave_config_info('canonical_host_type');
mext = 'mex';
izpc = false;
izmac = false;
if octave_config_info('mac'),
msub = 'mac';
izmac = true;
elseif octave_config_info('windows'),
msub = 'win';
izpc = true;
elseif octave_config_info('unix') && any(strfind(comp,'linux')),
msub = 'lin';
else
msub = 'unknown';
end
if ~isempty( msub ),
msub = [ 'o_', msub ];
if strncmp( comp, 'x86_64', 6 ),
msub = [ msub, '64' ];
else
msub = [ msub, '32' ];
end
end
else
comp = computer;
izpc = strncmp( comp, 'PC', 2 );
izmac = strncmp( comp, 'MAC', 3 );
mext = mexext;
msub = '';
end
if izpc,
fs = '\';
fsre = '\\';
ps = ';';
cs = false;
else
fs = '/';
fsre = '/';
ps = ':';
cs = ~izmac;
end
% Install location
mpath = mfilename('fullpath');
temp = strfind( mpath, fs );
mpath = mpath( 1 : temp(end) - 1 );
% Numeric version
nver = version;
nver(nver=='.') = ' ';
nver = sscanf(nver,'%d');
nver = nver(1) + 0.01 * ( nver(2) + 0.01 * nver(3) );
if isoctave || ~usejava('jvm'),
jver = 0;
else
jver = char(java.lang.System.getProperty('java.version'));
try
ndxs = strfind( jver, '.' );
jver = str2double( jver(1:ndxs(2)-1) );
catch
jver = 0;
end
end
cvx___.where = mpath;
cvx___.isoctave = isoctave;
cvx___.nver = nver;
cvx___.jver = jver;
cvx___.comp = comp;
cvx___.mext = mext;
cvx___.msub = msub;
cvx___.fs = fs;
cvx___.fsre = fsre;
cvx___.ps = ps;
cvx___.cs = cs;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Quick exit for non-verbose output %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if quick,
if nargout,
varargout = { fs, cvx___.ps, mpath, cvx___.mext };
end
cvx_load_prefs( false );
cvx___.loaded = true;
return
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Verbose output (cvx_setup, cvx_version plain) %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
cvx_ver = '2.1';
cvx_bld = '1123';
cvx_bdate = 'Sun Dec 17 18:58:10 2017';
cvx_bcomm = 'cff5298';
line = '---------------------------------------------------------------------------';
fprintf( '\n%s\n', line );
fprintf( 'CVX: Software for Disciplined Convex Programming (c)2014 CVX Research\n' );
fprintf( 'Version %3s, Build %4s (%7s)%42s\n', cvx_ver, cvx_bld, cvx_bcomm, cvx_bdate );
fprintf( '%s\n', line );
fprintf( 'Installation info:\n Path: %s\n', cvx___.where );
if isoctave,
fprintf( ' GNU Octave %s on %s\n', version, cvx___.comp );
else
verd = ver('MATLAB');
fprintf( ' MATLAB version: %s %s\n', verd.Version, verd.Release );
if usejava( 'jvm' ),
os_name = char(java.lang.System.getProperty('os.name'));
os_arch = char(java.lang.System.getProperty('os.arch'));
os_version = char(java.lang.System.getProperty('os.version'));
java_str = char(java.lang.System.getProperty('java.version'));
fprintf(' OS: %s %s version %s\n', os_name, os_arch, os_version );
fprintf(' Java version: %s\n', java_str );
else
fprintf( ' Architecture: %s\n', cvx___.comp );
fprintf( ' Java version: disabled\n' );
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Check for valid version %
%%%%%%%%%%%%%%%%%%%%%%%%%%%
issue = false;
isoctave = cvx___.isoctave;
nver = cvx___.nver;
if isoctave,
if nver <= 3.08,
fprintf( '%s\nCVX is not yet supported on Octave.\n(Please do not waste further time trying: changes to Octave are required.\nBut they are coming! Stay tuned.)\n%s\n', line, line );
issue = true;
end
elseif nver < 7.08 && strcmp( cvx___.comp(end-1:end), '64' ),
fprintf( '%s\nCVX requires MATLAB 7.8 or later (7.5 or later on 32-bit platforms).\n' , line, line );
issue = true;
elseif nver < 7.05,
fprintf( '%s\nCVX requires MATLAB 7.5 or later (7.8 or later on 64-bit platforms).\n' , line, line );
issue = true;
end
%%%%%%%%%%%%%%%%%%%%%%%%
% Verify file contents %
%%%%%%%%%%%%%%%%%%%%%%%%
fid = fopen( [ mpath, fs, 'MANIFEST' ], 'r' );
if fid > 0,
fprintf( 'Verfying CVX directory contents:' );
manifest = textscan( fid, '%s' );
manifest = manifest{1};
fclose( fid );
newman = get_manifest( mpath, fs );
if ~isequal( manifest, newman ),
missing = setdiff( manifest, newman );
additional = setdiff( newman, manifest );
if ~isempty( missing ) || ~isempty( additional ),
if fs ~= '/',
missing = strrep( missing, '/', fs );
additional = strrep( additional, '/', fs );
end
if ~isempty( missing ),
fprintf( '\n WARNING: The following files/directories are missing:\n' );
isdir = cellfun(@(x)x(end)==fs,missing);
missing_d = missing(isdir);
missing_f = missing(~isdir);
while ~isempty( missing_d ),
mdir = missing_d{1};
ss = strncmp( missing_d, mdir, length(mdir) );
tt = strncmp( missing_f, mdir, length(mdir) );
fprintf( ' %s%s%s + %d files, %d subdirectories\n', mpath, fs, mdir, nnz(tt), nnz(ss) - 1 );
missing_d(ss) = [];
missing_f(tt) = [];
end
for k = 1 : min(length(missing_f),10),
fprintf( ' %s%s%s\n', mpath, fs, missing_f{k} );
end
if length(missing_f) > 10,
fprintf( ' (and %d more files)\n', length(missing_f) - 10 );
end
fprintf( ' These omissions may prevent CVX from operating properly.\n' );
end
if ~isempty( additional ),
if isempty( missing ), fprintf( '\n' ); end
fprintf( ' WARNING: The following extra files/directories were found:\n' );
isdir = cellfun(@(x)x(end)==fs,additional);
issedumi = cellfun(@any,regexp( additional, [ '^sedumi.*[.]', mexext, '$' ] ));
additional_d = additional(isdir&~issedumi);
additional_f = additional(~isdir&~issedumi);
additional_s = additional(issedumi);
while ~isempty( additional_d ),
mdir = additional_d{1};
ss = strncmp( additional_d, mdir, length(mdir) );
tt = strncmp( additional_f, mdir, length(mdir) );
fprintf( ' %s%s%s + %d files, %d subdirectories\n', mpath, fs, mdir, nnz(tt), nnz(ss) - 1 );
additional_d(ss) = [];
additional_f(tt) = [];
end
for k = 1 : min(length(additional_f),10),
fprintf( ' %s%s%s\n', mpath, fs, additional_f{k} );
end
if length(additional_f) > 10,
fprintf( ' (and %d more files)\n', length(additional_f) - 10 );
end
fprintf( ' These files may alter the behavior of CVX in unsupported ways.\n' );
if ~isempty( additional_s ),
fprintf( ' ERROR: obsolete versions of SeDuMi MEX files were found:\n' );
for k = 1 : length(additional_s),
fprintf( ' %s%s%s\n', mpath, fs, additional_f{k} );
end
fprintf( ' These files are now obsolete, and must be removed to ensure\n' );
fprintf( ' that SeDuMi operates properly and produces sound results.\n' );
if ~issue,
fprintf( ' Please remove these files and re-run CVX_SETUP.\n' );
issue = true;
end
end
end
else
fprintf( '\n No missing files.\n' );
end
else
fprintf( '\n No missing files.\n' );
end
else
fprintf( 'Manifest missing; cannot verify file structure.\n' ) ;
end
if ~compile,
mexpath = [ mpath, fs, 'lib', fs ];
mext = cvx___.mext;
if ( ~exist( [ mexpath, 'cvx_eliminate_mex.', mext ], 'file' ) || ...
~exist( [ mexpath, 'cvx_bcompress_mex.', mext ], 'file' ) ) && ~issue,
issue = true;
if ~isempty( msub ),
mexpath = [ mexpath, msub, fs ];
issue = ~exist( [ mexpath, 'cvx_eliminate_mex.mex' ], 'file' ) || ...
~exist( [ mexpath, 'cvx_bcompress_mex.mex' ], 'file' );
end
if issue,
fprintf( ' ERROR: one or more MEX files for this platform are missing.\n' );
fprintf( ' These files end in the suffix ".%s". CVX will not operate\n', mext );
fprintf( ' without these files. Please visit\n' );
fprintf( ' http://cvxr.com/cvx/download\n' );
fprintf( ' And download a distribution targeted for your platform.\n' );
end
end
end
%%%%%%%%%%%%%%%
% Preferences %
%%%%%%%%%%%%%%%
cvx_load_prefs( true );
%%%%%%%%%%%%%%%%
% License file %
%%%%%%%%%%%%%%%%
if isoctave,
if ~isempty( cvx___.license ),
fprintf( 'CVX Professional is not supported with Octave.\n' );
end
elseif cvx___.jver < 1.6,
fprintf(' WARNING: full support for CVX Professional licenses\n' );
fprintf(' requres Java version 1.6.0 or later. Please upgrade.\n' );
elseif exist( 'cvx_license', 'file' ),
cvx_license( args{:} );
end
%%%%%%%%%%%%%%%
% Wrapping up %
%%%%%%%%%%%%%%%
if ~issue,
cvx___.loaded = true;
end
clear fs;
fprintf( '%s\n', line );
if length(dbstack) <= 1,
fprintf( '\n' );
end
%%%%%%%%%%%%%%%%%%%%%%
% Preference loading %
%%%%%%%%%%%%%%%%%%%%%%
function cvx_load_prefs( verbose )
global cvx___
fs = cvx___.fs;
isoctave = cvx___.isoctave;
errmsg = '';
if verbose,
fprintf( 'Preferences: ' );
end
if isoctave,
pfile = [ prefdir, fs, '.cvx_prefs.mat' ];
else
pfile = [ regexprep( prefdir(1), [ cvx___.fsre, 'R\d\d\d\d\w$' ], '' ), fs, 'cvx_prefs.mat' ];
end
outp = [];
try
if exist( pfile, 'file' )
outp = load( pfile );
pfile2 = pfile;
elseif ~isoctave,
pfile2 = [ prefdir, fs, 'cvx_prefs.mat' ];
if exist( pfile2, 'file' ),
outp = load( pfile2 );
end
end
catch errmsg
errmsg = cvx_error( errmsg, 67, false, ' ' );
errmsg = sprintf( 'CVX encountered the following error attempting to load your preferences:\n%sPlease attempt to diagnose this error and try again.\nYou may need to re-run CVX_SETUP as well.\nIn the meanwhile, preferences will be set to their defaults.\n', errmsg );
end
if ~isempty( outp ),
try
cvx___.expert = outp.expert;
cvx___.precision = outp.precision;
cvx___.precflag = outp.precflag;
cvx___.rat_growth = outp.rat_growth;
cvx___.path = outp.path;
cvx___.solvers = outp.solvers;
cvx___.license = outp.license;
catch
outp = [];
errmsg = 'Your CVX preferences file seems out of date; default preferences will be used.';
end
end
if isempty( outp ),
cvx___.expert = false;
cvx___.precision = [eps^0.5,eps^0.5,eps^0.25];
cvx___.precflag = 'default';
cvx___.rat_growth = 10;
cvx___.path = [];
cvx___.solvers = [];
cvx___.license = [];
end
cvx___.pfile = pfile;
if verbose,
if ~isempty( errmsg ),
fprintf( 'error during load:\n%s', cvx_error( errmsg, 70, false, ' ' ) );
elseif isempty( cvx___.path ),
fprintf( 'none found; defaults loaded.\n' );
else
fprintf( '\n Path: %s\n', pfile2 );
end
elseif ~isempty( errmsg ),
warning( 'CVX:BadPrefsLoad', errmsg );
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Recursive manifest building function %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function newman = get_manifest( mpath, fs )
dirs = {};
files = {};
nfiles = dir( mpath );
ndir = '';
dndx = 0;
pat2 = '^\.|~$|';
pat = '^\.|~$|^cvx_license.[md]at$|^doc$|^examples$';
while true,
isdir = [ nfiles.isdir ];
nfiles = { nfiles.name };
tt = cellfun( @isempty, regexp( nfiles, pat ) ); pat = pat2;
isdir = isdir(tt);
nfiles = nfiles(tt);
ndirs = nfiles(isdir);
if ~isempty(ndirs),
dirs = horzcat( dirs, strcat(strcat(ndir,ndirs), fs ) ); %#ok
end
nfiles = nfiles(~isdir);
if ~isempty(nfiles),
files = horzcat( files, strcat(ndir,nfiles) ); %#ok
end
if length( dirs ) == dndx, break; end
dndx = dndx + 1;
ndir = dirs{dndx};
nfiles = dir( [ mpath, fs, ndir ] );
end
[tmp,ndxs1] = sort(upper(dirs)); %#ok
[tmp,ndxs2] = sort(upper(files)); %#ok
newman = horzcat( dirs(ndxs1), files(ndxs2) );
if fs ~= '/',
newman = strrep( newman, fs, '/' );
end
newman = newman(:);
% Copyright 2005-2016 CVX Research, Inc.
% See the file LICENSE.txt for full copyright information.
% The command 'cvx_where' will show where this file is located.
|
github
|
xiaoxiaojiangshang/Programs-master
|
cvx_grbgetkey.m
|
.m
|
Programs-master/matlab/cvx/cvx_grbgetkey.m
| 19,096 |
utf_8
|
080162e4fd27b14ea8387362148db7d1
|
function success = cvx_grbgetkey( kcode, overwrite )
% CVX_GRBGETKEY Retrieves and saves a Gurobi/CVX license.
%
% This function is used to install Gurobi license keys for use in CVX. It
% is called with your Gurobi license code as a string argument; e.g.
%
% cvx_grbgetkey xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
% cvx_grbgetkey( 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' )
%
% If you have not yet obtained a Gurobi license code, please visit the page
%
% <a href="matlab: web('http://www.gurobi.com/documentation/5.5/quick-start-guide/node5','-browser');">http://www.gurobi.com/documentation/5.5/quick-start-guide/node5</a>
%
% for information on your various options (trial, academic, commercial).
% Once you have received notice that your license has been created, visit
% the Gurobi license page
%
% <a href="matlab: web('http://www.gurobi.com/download/licenses/current','-browser');">http://www.gurobi.com/download/licenses/current</a>
%
% to retrieve the 36-character license code.
%
% The retrieved Gurobi license will be stored in your MATLAB preferences
% directory (see the PREFDIR command) on Mac and Linux, and your home
% directory on Windows. If a license file already exists at this location,
% and its expiration date has not yet passed, CVX_GRBGETKEY will refuse to
% retrieve a new license. To override this behavior, call the function
% with an -OVERWRITE argument:
%
% cvx_grbgetkey xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx -overwrite
% cvx_grbgetkey( 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', '-overwrite' )
%
% Note that this utility is meant to retrieve licenses for the version of
% Gurobi that is bundled with CVX. While it will retrieve full licenses as
% well, it is strongly recommended that you move such licenses to one of the
% standard Gurobi locations, discussed here:
%
% <a href="matlab: web(''http://www.gurobi.com/documentation/5.5/quick-start-guide/node8'',''-browser'');">http://www.gurobi.com/documentation/5.5/quick-start-guide/node8</a>
%
% Note that in order to use Gurobi with CVX, *both* a Gurobi license and a
% CVX Professional license are required.
if exist( 'OCTAVE_VERSION', 'builtin' ),
error( 'CVX:NoOctave', 'CVX_GRBGETKEY cannot be used with Octave.' );
end
fs = filesep;
mpath = mfilename('fullpath');
temp = strfind( mpath, fs );
mpath = mpath( 1 : temp(end) - 1 );
mext = mexext;
success = true;
line = '---------------------------------------------------------------------------';
jprintf({
''
line
'CVX/Gurobi license key installer'
line
});
%%%%%%%%%%%%%%%%%%%%%%%%%
% Process the arguments %
%%%%%%%%%%%%%%%%%%%%%%%%%
if nargin == 2 && ischar( kcode ) && size( kcode, 1 ) == 1 && kcode(1) == '-',
tmp = kcode;
kcode = overwrite;
overwrite = tmp;
end
emsg = [];
if nargin < 1,
emsg = '';
elseif isempty( kcode ) || ~ischar( kcode ) || ndims( kcode ) > 2 || size( kcode, 1 ) ~= 1, %#ok
emsg = 'Invalid license code: must be a string.';
elseif ~regexp( kcode, '^[0-9a-f]{8,8}-[0-9a-f]{4,4}-[0-9a-f]{4,4}-[0-9a-f]{4,4}-[0-9a-f]{12,12}$', 'once' )
emsg = sprintf( 'Invalid license code: %s', kcode );
elseif nargin < 2 || isempty( overwrite ),
overwrite = false;
elseif isequal( overwrite, '-overwrite' ),
overwrite = true;
elseif ischar( overwrite ) && size( overwrite, 1 ) == 1,
emsg = sprintf( 'Invalid argument: %s', overwrite );
else
emsg = 'Invalid second argument.';
end
if ischar( emsg ),
if ~isempty( emsg ),
fprintf( '*** %s\n\n', emsg );
end
jprintf({
'This function is used to install Gurobi license keys for use in CVX. It'
'is called with your license code as an argument; e.g.'
''
' %s xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
' %s( ''xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'' )'
''
'If you have not yet obtained a license code, please visit the page'
''
' <a href="matlab: web(''http://www.gurobi.com/documentation/5.5/quick-start-guide/node5'',''-browser'');">http://www.gurobi.com/documentation/5.5/quick-start-guide/node5</a>'
''
'for information on your various options (trial, academic, commercial). Once'
'a license has been created, you may retrieve its 36-character code by'
'logging into your Gurobi account and visiting the page'
''
' <a href="matlab: web(''http://www.gurobi.com/download/licenses/current'',''-browser'');">http://www.gurobi.com/download/licenses/current</a>'
''
}, mfilename, mfilename );
success = false;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Check to see if Gurobi is present %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if success,
if fs == '\', fsre = '\\'; else fsre = fs; end
gname = [ mpath, fs, 'gurobi' ];
if ~exist( gname, 'dir' ),
jprintf({
'This function is meant to be used only with the version of Gurobi that is'
'bundled with CVX; but your CVX installation does not include Gurobi.'
'To rectify this, you may either download a CVX/Gurobi bundle from'
''
' <a href="matlab: web(''http://cvxr.com/cvx/download'',''-browser'');">http://cvxr.com/cvx/download</a>'
''
'or download the full Gurobi package from Gurobi directly:'
''
' <a href="matlab: web(''http://www.gurobi.com'',''-browser'');">http://www.gurobi.com</a>'
''
'In either case, you will need both a CVX Professional license and a Gurobi'
'license to proceed.'
});
success = false;
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Ensure that this platform is compatible with the bundled Gurobi solver %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if success,
gname = [ gname, fs, mext(4:end) ];
if ~exist( gname, 'dir' ),
mismatch = false;
switch mext,
case 'mexmaci', pform = '32-bit OSX';
case 'glx', pform = '32-bit Linux';
case 'a64', pform = '64-bit Linux'; mismatch = true;
case 'maci64', pform = '64-bit OSX'; mismatch = true;
case 'w32', pform = '32-bit Windows'; mismatch = true;
case 'w64', pform = '64-bit Windows'; mismatch = true;
otherwise, pform = [];
end
if mismatch,
jprintf({
'The %s version of Gurobi is missing, perhaps because you downloaded a CVX'
'package for a different MATLAB platform. Please visit'
''
' <a href="matlab: web(''http://cvxr.com/cvx/download'',''-browser'');">http://cvxr.com/cvx/download</a>'
''
'and download and install the correct package.'
}, pform );
elseif isempty( pform ),
fprintf( 'CVX/Gurobi is not supported on the %s platform.\n', computer );
else
fprintf( 'CVX/Gurobi is not supported on %s. Consider using the 64-bit version of MATLAB.\n', pform );
end
success = false;
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Confirm the existence of the grbgetkey utility %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if success,
gname = [ gname, fs, 'grbgetkey' ];
if fs == '\',
gname = [ gname, '.exe' ];
end
if ~exist( gname, 'file' ),
jprintf({
'Your CVX package is missing the file'
''
' %s'
''
'which is necessary to complete this task. Please reinstall CVX.'
}, gname );
success = false;
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Create the preferences directory, if necessary %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if success,
fdir = regexprep( prefdir, [ fsre, 'R\d\d\d\d\w*$' ], '' );
if ~exist( fdir, 'dir' ),
[success,msg] = mkdir( fdir );
if ~success,
jprintf({
'This function needs to write to the directory'
''
' %s'
''
'which does not exist. An attempt to create it resulted in this error:'
''
' %s'
''
'Please rectify this problem and try again.'
}, fdir, msg );
success = false;
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Guard against overwriting an existing license %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if success,
% We actually use the parent directory of 'prefdir' if that directory has
% the standard version format: e.g., if prefdir is ~/joe/.matlab/R2012b,
% we store our data in ~/joe/.matlab, so that all versions of MATLAB can
% see the same CVX data.
fname = [ fdir, fs, 'cvx_gurobi.lic' ];
if exist( fname, 'file' ),
if overwrite,
msg = [];
else
msg = 'This license may or may not be current.';
fid = fopen( fname );
if fid ~= 0,
fstr = fread( fid, Inf, 'uint8=>char' )';
fclose( fid );
matches = regexp( fstr, 'EXPIRATION=\d\d\d\d-\d\d-\d\d', 'once' );
if matches && floor(datenum(fstr(matches+11:matches+20),'yyyy-mm-dd'))<floor(datenum(clock))
msg = [];
else
msg = 'This license has not yet expired.';
end
end
end
if ~isempty( msg )
jprintf({
'An existing license file has been found at location:'
''
' %s'
''
'%s If you wish to overwrite this file,'
'please re-run this function with an "-overwrite" argument: that is,'
''
' %s %s -overwrite'
' %s( ''%s'', ''-overwrite'' )'
''
'Otherwise, please move the existing license and try again.'
}, fname, msg, mfilename, kcode, mfilename, kcode );
success = false;
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Create a temporary destination directory %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
tdir = [];
if success,
for k = 1 : 10,
tdir = tempname;
if ~exist( tdir, 'file' ), break; end
end
[success,msg] = mkdir(tdir);
if ~success,
jprintf({
'This function attempted to create the temporary directory'
''
' %s'
''
'but the following error occurred:'
''
' %s'
''
'Please rectify the problem and try again.';
}, tdir, msg );
success = false;
tdir = [];
end
end
%%%%%%%%%%%%%%%%%%%%%%%%
% Download the license %
%%%%%%%%%%%%%%%%%%%%%%%%
if success
fprintf( 'Contacting the Gurobi Optimization license server...' );
[status,result]=system( sprintf( '%s --path=%s %s', gname, tdir, kcode ) ); %#ok
fprintf( 'done.\n' );
if any( strfind( result, 'Unable to determine hostname' ) ) || any( strfind( result, 'not recognized as belonging to an academic domain' ) ),
jprintf({
'The attempt to retrieve the license key failed with the following error'
'while trying to verify your academic license eligibility:'
''
' %s'
'For information about this error, please consult the Gurobi documentation'
''
' <a href="matlab: web(''http://www.gurobi.com/documentation/5.5/quick-start-guide/node5'',''-browser'');">http://www.gurobi.com/documentation/5.5/quick-start-guide/node5</a>'
''
'Once you have rectified the error, please try again.'
}, regexprep(result,'.*---------------------\n+(.*?)\n+$','$1') );
success = false;
elseif any( strfind( result, 'already issued for host' ) )
matches = regexp( fstr, 'already issued for host ''([^'']+)''', 'once' );
if ~isempty( matches ),
matches = sprintf( ' (%s)', matches{1}{1} );
else
matches = '';
end
jprintf({
'This license has already been issued for a different host%s.'
'Please acquire a new license for this host from Gurobi.'
}, matches );
success = false;
elseif ~any( strfind( result, 'License key saved to file' ) ),
jprintf({
'The attempt to retrieve the license key failed with the following error:'
''
' %s'
'For information about this error, please consult the Gurobi documentation'
''
' <a href="matlab: web(''http://www.gurobi.com/documentation/5.5/quick-start-guide/node5'',''-browser'');">http://www.gurobi.com/documentation/5.5/quick-start-guide/node5</a>'
''
'Once you have rectified the error, please try again.'
}, regexprep(result,'.*---------------------\n+(.*?)\n+$','$1') );
fprintf( '%s\n', line );
fprintf( result(1+(result(1)==10):end) );
success = false;
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Read the license file to determine its expiration %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if success,
tname = [ tdir, fs, 'gurobi.lic' ];
[fid,msg] = fopen( tname, 'r' );
if fid == 0,
jprintf({
'An unexpected error occured: the Gurobi license file could not be'
'opened. The file was expected to be in the temporary location'
''
' %s'
''
'but the attempt to read it resulted in the following error:'
''
' %s'
''
'Please attempt to rectify the problem and try again; if necessary,'
'please contact <a href="mailto:[email protected]">CVX support</a>.'
}, tname, msg );
success = false;
tdir = [];
else
fstr = fread( fid, Inf, 'uint8=>char' )';
fclose( fid );
matches = regexp( fstr, 'EXPIRATION=\d\d\d\d-\d\d-\d\d', 'once' );
if matches,
if floor(datenum(fstr(matches+11:matches+20),'yyyy-mm-dd'))<floor(datenum(clock))
jprintf({
'The license was successfully downloaded, but it expired on %s.'
'Please contact Gurobi for a new license.'
}, fstr(matches+11:matches+20) );
success = false;
else
jprintf({
'Download successful. The license can be found at'
''
' %s'
''
'The license will expire at the end of the day on %s.'
}, fname, fstr(matches+11:matches+20) );
end
end
if success,
matches = regexp( fstr, '\nAPPNAME=CVX\n', 'once' );
if ~any( matches ),
[ matches, mends ] = regexp( fstr, '\nAPPNAME=\w+', 'start', 'end' );
if any( matches ),
jprintf({
line
'ERROR: This license is reserved for the application "%s" and will'
'*not* work with CVX. We strongly recommend that you move this license to'
'another location, in accordance with this documentation:'
''
' <a href="matlab: web(''http://www.gurobi.com/documentation/5.5/quick-start-guide/node8'',''-browser'');">http://www.gurobi.com/documentation/5.5/quick-start-guide/node8</a>'
''
'To use Gurobi with CVX, you must either obtain a full Gurobi license or a'
'CVX specific license.'
}, fstr(matches(1)+9:mends) );
success = false;
else
if ispc,
cmd = ' movefile(''%s'',''%sgurobi.lic'')';
fdr = getenv('USERPROFILE');
if fdr(end) ~= '\', fdr(end+1) = '\'; end
else
cmd = ' movefile %s %sgurobi.lic';
fdr = '~/';
end
jprintf({
line
'WARNING: This license is not a CVX-specific license. It will still work with'
'CVX; however, if you also wish to use it with other applications, then we'
'strongly recommend that you copy it to a standard Gurobi location. Consult'
'the following Gurobi documentation for more information:'
''
' <a href="matlab: web(''http://www.gurobi.com/documentation/5.5/quick-start-guide/node8'',''-browser'');">http://www.gurobi.com/documentation/5.5/quick-start-guide/node8</a>'
''
'For instance, to move this file to the standard home directory location,'
'copy and paste this command into your MATLAB command line:'
''
cmd
}, fname, fdr );
end
end
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Move the license to its proper location %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if success,
[success,msg] = movefile( tname, fname, 'f' );
if ~success,
jprintf({
'The attempt to move the Gurobi license file from its temporary location'
''
' %s'
''
'to its final location'
''
' %s'
''
'resulted in the following error:'
''
' %s'
''
'Please rectify the problem and try again; or move the file manually. Once'
'the license is in place, please run CVX_SETUP to configure CVX to use the'
'Gurobi solver with the new license.'
}, tname, fname, msg );
success = false;
end
end
%%%%%%%%%%%%
% Clean up %
%%%%%%%%%%%%
if ~isempty(tdir),
[success,message] = rmdir( tdir, 's' ); %#ok
end
if success,
jprintf({
line
'Now that the license has been retrieved, please run CVX_SETUP to configure'
'CVX to use the Gurobi solver with the new license.'
});
end
jprintf({
line
''
});
if nargout == 0,
clear success
end
function jprintf( strs, varargin )
strs = strs(:)';
[ strs{2,:} ] = deal( '\n' );
fprintf( cat(2,strs{:}), varargin{:} );
% Copyright 2014 CVX Research, Inc.
% This file is governed by the terms of the CVX Professional license;
% redistribution is *not* permitted. Please see the file LICENSE.txt for
% full copyright information.
% The command 'cvx_where' will show where this file is located.
|
github
|
xiaoxiaojiangshang/Programs-master
|
HSDNTcorr.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/HSDSolver/HSDNTcorr.m
| 1,001 |
utf_8
|
c42eba1c6bae660b88921b7c8747490e
|
%%************************************************************************
%% HSDNTcorr: corrector step for the NT direction.
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%************************************************************************
function [par,dX,dy,dZ,resnrm] = HSDNTcorr(blk,At,par,rp,Rd,sigmu,hRd,...
dX,dZ,coeff,L,X,Z)
global printlevel
global solve_ok
%%
[rhs,EinvRc] = HSDNTrhsfun(blk,At,par,X,Z,rp,Rd,sigmu,hRd,dX,dZ);
m = length(rp); ncolU = size(coeff.mat12,2);
rhs = [rhs; zeros(m+ncolU-length(rhs),1)];
%%
solve_ok = 1; %#ok
[xx,resnrm,solve_ok] = HSDbicgstab(coeff,rhs,L,[],[],printlevel);
if (solve_ok<=0) && (printlevel)
fprintf('\n warning: iterative solver fails: %3.1f.',solve_ok);
end
if (par.printlevel>=3); fprintf(' %2.0f',length(resnrm)-1); end
%%
[par,dX,dy,dZ] = HSDNTdirfun(blk,At,par,Rd,EinvRc,xx);
%%************************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
HSDHKMdirfun.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/HSDSolver/HSDHKMdirfun.m
| 1,551 |
utf_8
|
1034e25e48a42d2fa143f93f47961fe9
|
%%*******************************************************************
%% HSDHKMdirfun: compute (dX,dZ), given dy, for the HKM direction.
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%*******************************************************************
function [par,dX,dy,dZ] = HSDHKMdirfun(blk,At,par,Rd,EinvRc,X,xx)
global solve_ok
dX = cell(size(blk,1),1); dZ = cell(size(blk,1),1); dy = [];
if (any(isnan(xx)) || any(isinf(xx)))
solve_ok = 0;
fprintf('\n HSDHKMdirfun: solution contains NaN or inf.');
return;
end
%%
m = par.m;
dy2 = xx(1:m+2);
%%
for p=1:size(blk,1)
pblk = blk(p,:);
if strcmp(pblk{1},'l')
dZ(p) = ops(Rd(p),'-',Atyfun(pblk,At(p,:),[],[],dy2));
dX{p} = EinvRc{p} - par.dd{p}.*dZ{p};
elseif strcmp(pblk{1},'q')
dZ(p) = ops(Rd(p),'-',Atyfun(pblk,At(p,:),[],[],dy2));
tmp = par.dd{p}.*dZ{p} ...
+ qops(pblk,qops(pblk,dZ{p},par.Zinv{p},1),X{p},3) ...
+ qops(pblk,qops(pblk,dZ{p},X{p},1),par.Zinv{p},3);
dX{p} = EinvRc{p} - tmp;
elseif strcmp(pblk{1},'s')
dZ(p) = ops(Rd(p),'-',Atyfun(pblk,At(p,:),par.permA(p,:),par.isspAy(p),dy2));
tmp = Prod3(pblk,X{p},dZ{p},par.Zinv{p},0);
tmp = 0.5*(tmp+tmp');
dX{p} = EinvRc{p}-tmp;
end
end
dy = dy2(1:m);
par.dtau = dy2(m+1);
par.dtheta = dy2(m+2);
par.dkap = (par.mu./par.tau - par.kap) - par.kap*(par.dtau/par.tau);
%%*******************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
HSDsqlp.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/HSDSolver/HSDsqlp.m
| 11,860 |
utf_8
|
00b8311a8efbee36662ca9288870a1cd
|
%%*****************************************************************************
%% HSDsqlp: solve an semidefinite-quadratic-linear program
%% by infeasible path-following method on the homogeneous self-dual model.
%%
%% [obj,X,y,Z,info,runhist] =
%% HSDsqlp(blk,At,C,b,OPTIONS,X0,y0,Z0);
%%
%% Input: blk: a cell array describing the block diagonal structure of SQL data.
%% At: a cell array with At{p} = [svec(Ap1) ... svec(Apm)]
%% b,C: data for the SQL instance.
%% OPTIONS: a structure that specifies parameters required in HSDsqlp.m,
%% (if it is not given, the default in sqlparameters.m is used).
%%
%% (X0,y0,Z0): an initial iterate (if it is not given, the default is used).
%%
%% Output: obj = [<C,X> <b,y>].
%% (X,y,Z): an approximately optimal solution or a primal or dual
%% infeasibility certificate.
%% info.termcode = termination-code
%% info.iter = number of iterations
%% info.obj = [primal-obj, dual-obj]
%% info.cputime = total-time
%% info.gap = gap
%% info.pinfeas = primal_infeas
%% info.dinfeas = dual_infeas
%% runhist.pobj = history of primal objective value.
%% runhist.dobj = history of dual objective value.
%% runhist.gap = history of <X,Z>.
%% runhist.pinfeas = history of primal infeasibility.
%% runhist.dinfeas = history of dual infeasibility.
%% runhist.cputime = history of cputime spent.
%%----------------------------------------------------------------------------
%% The OPTIONS structure specifies the required parameters:
%% vers gam predcorr expon gaptol inftol steptol
%% maxit printlevel ...
%% (all have default values set in sqlparameters.m).
%%
%%*************************************************************************
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%*************************************************************************
function [obj,X,y,Z,info,runhist] = ...
HSDsqlp(blk,At,C,b,OPTIONS,X0,y0,Z0,kap0,tau0,theta0)
if (nargin < 5); OPTIONS = []; end
isemptyAtb = 0;
if isempty(At) && isempty(b);
%% Add redundant constraint: <-I,X> <= 0
b = 0;
At = ops(ops(blk,'identity'),'*',-1);
numblk = size(blk,1);
blk{numblk+1,1} = 'l'; blk{numblk+1,2} = 1;
At{numblk+1,1} = 1; C{numblk+1,1} = 0;
isemptyAtb = 1;
end
%%
%%-----------------------------------------
%% get parameters from the OPTIONS structure.
%%-----------------------------------------
%%
% warning off;
matlabversion = sscanf(version,'%f');
if strcmp(computer,'PCWIN64') || strcmp(computer,'GLNXA64')
par.computer = 64;
else
par.computer = 32;
end
par.matlabversion = matlabversion(1);
par.vers = 0;
par.predcorr = 1;
par.gam = 0;
par.expon = 1;
par.gaptol = 1e-8;
par.inftol = 1e-8;
par.steptol = 1e-6;
par.maxit = 100;
par.printlevel = 3;
par.stoplevel = 1;
par.scale_data = 0;
par.spdensity = 0.4;
par.rmdepconstr = 0;
par.smallblkdim = 50;
par.schurfun = cell(size(blk,1),1);
par.schurfun_par = cell(size(blk,1),1);
%%
parbarrier = cell(size(blk,1),1);
for p = 1:size(blk,1)
pblk = blk(p,:);
if strcmp(pblk{1},'s') || strcmp(pblk{1},'q')
parbarrier{p} = zeros(1,length(pblk{2}));
elseif strcmp(pblk{1},'l') || strcmp(pblk{1},'u' )
parbarrier{p} = zeros(1,sum(pblk{2}));
end
end
parbarrier_0 = parbarrier;
%%
if nargin > 4,
if isfield(OPTIONS,'vers'); par.vers = OPTIONS.vers; end
if isfield(OPTIONS,'predcorr'); par.predcorr = OPTIONS.predcorr; end
if isfield(OPTIONS,'gam'); par.gam = OPTIONS.gam; end
if isfield(OPTIONS,'expon'); par.expon = OPTIONS.expon; end
if isfield(OPTIONS,'gaptol'); par.gaptol = OPTIONS.gaptol; end
if isfield(OPTIONS,'inftol'); par.inftol = OPTIONS.inftol; end
if isfield(OPTIONS,'steptol'); par.steptol = OPTIONS.steptol; end
if isfield(OPTIONS,'maxit'); par.maxit = OPTIONS.maxit; end
if isfield(OPTIONS,'printlevel'); par.printlevel = OPTIONS.printlevel; end
if isfield(OPTIONS,'stoplevel'); par.stoplevel = OPTIONS.stoplevel; end
if isfield(OPTIONS,'scale_data'); par.scale_data = OPTIONS.scale_data; end
if isfield(OPTIONS,'spdensity'); par.spdensity = OPTIONS.spdensity; end
if isfield(OPTIONS,'rmdepconstr'); par.rmdepconstr = OPTIONS.rmdepconstr; end
if isfield(OPTIONS,'smallblkdim'); par.smallblkdim = OPTIONS.smallblkdim; end
if isfield(OPTIONS,'parbarrier');
parbarrier = OPTIONS.parbarrier;
if isempty(parbarrier); parbarrier = parbarrier_0; end
if ~iscell(parbarrier);
tmp = parbarrier; clear parbarrier; parbarrier{1} = tmp;
end
if (length(parbarrier) < size(blk,1))
len = length(parbarrier);
parbarrier(len+1:size(blk,1)) = parbarrier_0(len+1:size(blk,1));
end
end
if isfield(OPTIONS,'schurfun');
par.schurfun = OPTIONS.schurfun;
if ~isempty(par.schurfun); par.scale_data = 0; end
end
if isfield(OPTIONS,'schurfun_par'); par.schurfun_par = OPTIONS.schurfun_par; end
if isempty(par.schurfun); par.schurfun = cell(size(blk,1),1); end
if isempty(par.schurfun_par); par.schurfun_par = cell(size(blk,1),1); end
end
if (size(blk,2) > 2); par.smallblkdim = 0; end
%%
%%-----------------------------------------
%% convert matrices to cell arrays.
%%-----------------------------------------
%%
if ~iscell(At); At = {At}; end;
if ~iscell(C); C = {C}; end;
if all(size(At) == [size(blk,1), length(b)]);
convertyes = zeros(size(blk,1),1);
for p = 1:size(blk,1)
if strcmp(blk{p,1},'s') && all(size(At{p,1}) == sum(blk{p,2}))
convertyes(p) = 1;
end
end
if any(convertyes)
if (par.printlevel);
fprintf('\n sqlp: converting At into required format');
end
At = svec(blk,At,ones(size(blk,1),1));
end
end
%%
%%-----------------------------------------
%% validate SQLP data.
%%-----------------------------------------
%%
% tstart = cputime;
[blk,At,C,b,blkdim,numblk] = validate(blk,At,C,b,par);
[blk,At,C,b,iscmp] = convertcmpsdp(blk,At,C,b);
if (iscmp) && (par.printlevel>=2)
fprintf('\n SQLP has complex data');
end
if (nargin <= 5) || (isempty(X0) || isempty(y0) || isempty(Z0));
if (max([ops(At,'norm'),ops(C,'norm'),norm(b)]) > 1e2)
[X0,y0,Z0] = infeaspt(blk,At,C,b,1);
else
[X0,y0,Z0] = infeaspt(blk,At,C,b,2,1);
end
end
if ~iscell(X0); X0 = {X0}; end;
if ~iscell(Z0); Z0 = {Z0}; end;
if (length(y0) ~= length(b))
error('HSDsqlp: length of b and y0 not compatible');
end
[X0,Z0] = validate_startpoint(blk,X0,Z0,par.spdensity);
%%
if (nargin <= 8) || (isempty(kap0) || isempty(tau0) || isempty(theta0))
if (max([ops(At,'norm'),ops(C,'norm'),norm(b)]) > 1e6)
kap0 = 10*blktrace(blk,X0,Z0);
else
kap0 = blktrace(blk,X0,Z0);
end
tau0 = 1; theta0 = 1;
end
%%
if (par.printlevel>=2)
fprintf('\n num. of constraints = %2.0d',length(b));
if blkdim(1);
fprintf('\n dim. of sdp var = %2.0d,',blkdim(1));
fprintf(' num. of sdp blk = %2.0d',numblk(1));
end
if blkdim(2);
fprintf('\n dim. of socp var = %2.0d,',blkdim(2));
fprintf(' num. of socp blk = %2.0d',numblk(2));
end
if blkdim(3); fprintf('\n dim. of linear var = %2.0d',blkdim(3)); end
if blkdim(4); fprintf('\n dim. of free var = %2.0d',blkdim(4)); end
end
%%
%%-----------------------------------------
%% detect unrestricted blocks in linear blocks
%%-----------------------------------------
%%
user_supplied_schurfun = 0;
for p = 1:size(blk,1)
if ~isempty(par.schurfun{p}); user_supplied_schurfun = 1; end
end
if (user_supplied_schurfun == 0)
[blk2,At2,C2,ublkinfo,parbarrier2,X02,Z02] = ...
detect_ublk(blk,At,C,parbarrier,X0,Z0,par.printlevel);
else
blk2 = blk; At2 = At; C2 = C;
parbarrier2 = parbarrier; X02 = X0; Z02 = Z0;
ublkinfo = cell(size(blk2,1),1);
end
ublksize = blkdim(4);
for p = 1:size(ublkinfo,1)
ublksize = ublksize + length(ublkinfo{p});
end
%%
%%-----------------------------------------
%% detect diagonal blocks in semidefinite blocks
%%-----------------------------------------
%%
if (user_supplied_schurfun==0)
[blk3,At3,C3,diagblkinfo,diagblkchange,parbarrier3,X03,Z03] = ...
detect_lblk(blk2,At2,C2,b,parbarrier2,X02,Z02,par.printlevel); %#ok
else
blk3 = blk2; At3 = At2; C3 = C2;
% parbarrier3 = parbarrier2;
X03 = X02; Z03 = Z02;
diagblkchange = 0;
diagblkinfo = cell(size(blk3,1),1);
end
%%
%%-----------------------------------------
%% main solver
%%-----------------------------------------
%%
%exist_analytic_term = 0;
%for p = 1:size(blk3,1);
% idx = find(parbarrier3{p} > 0);
% if ~isempty(idx); exist_analytic_term = 1; end
%end
%%
if (par.vers == 0);
if blkdim(1); par.vers = 1; else par.vers = 2; end
end
par.blkdim = blkdim;
par.ublksize = ublksize;
[obj,X3,y,Z3,info,runhist] = ...
HSDsqlpmain(blk3,At3,C3,b,par,X03,y0,Z03,kap0,tau0,theta0);
%%
%%-----------------------------------------
%% recover semidefinite blocks from linear blocks
%%-----------------------------------------
%%
if any(diagblkchange)
X2 = cell(size(blk2,1),1); Z2 = cell(size(blk2,1),1);
count = 0;
for p = 1:size(blk2,1)
pblk = blk2(p,:);
n = sum(pblk{2});
blkno = diagblkinfo{p,1};
idxdiag = diagblkinfo{p,2};
idxnondiag = diagblkinfo{p,3};
if ~isempty(idxdiag)
len = length(idxdiag);
Xtmp = [idxdiag,idxdiag,X3{end}(count+1:count+len); n, n, 0];
Ztmp = [idxdiag,idxdiag,Z3{end}(count+1:count+len); n, n, 0];
if ~isempty(idxnondiag)
[ii,jj,vv] = find(X3{blkno});
Xtmp = [Xtmp; idxnondiag(ii),idxnondiag(jj),vv]; %#ok
[ii,jj,vv] = find(Z3{blkno});
Ztmp = [Ztmp; idxnondiag(ii),idxnondiag(jj),vv]; %#ok
end
X2{p} = spconvert(Xtmp);
Z2{p} = spconvert(Ztmp);
count = count + len;
else
X2(p) = X3(blkno); Z2(p) = Z3(blkno);
end
end
else
X2 = X3; Z2 = Z3;
end
%%
%%-----------------------------------------
%% recover linear block from unrestricted block
%%-----------------------------------------
%%
numblk = size(blk,1);
numblknew = numblk;
X = cell(numblk,1); Z = cell(numblk,1);
for p = 1:numblk
n = blk{p,2};
if isempty(ublkinfo{p,1})
X{p} = X2{p}; Z{p} = Z2{p};
else
Xtmp = zeros(n,1); Ztmp = zeros(n,1);
Xtmp(ublkinfo{p,1}) = max(0,X2{p});
Xtmp(ublkinfo{p,2}) = max(0,-X2{p});
Ztmp(ublkinfo{p,1}) = max(0,Z2{p});
Ztmp(ublkinfo{p,2}) = max(0,-Z2{p});
if ~isempty(ublkinfo{p,3})
numblknew = numblknew + 1;
Xtmp(ublkinfo{p,3}) = X2{numblknew};
Ztmp(ublkinfo{p,3}) = Z2{numblknew};
end
X{p} = Xtmp; Z{p} = Ztmp;
end
end
%%
%%-----------------------------------------
%% recover complex solution
%%-----------------------------------------
%%
if (iscmp)
for p = 1:numblk
pblk = blk(p,:);
n = sum(pblk{2})/2;
if strcmp(pblk{1},'s');
X{p} = X{p}(1:n,1:n) + sqrt(-1)*X{p}(n+1:2*n,1:n);
Z{p} = Z{p}(1:n,1:n) + sqrt(-1)*Z{p}(n+1:2*n,1:n);
X{p} = 0.5*(X{p}+X{p}');
Z{p} = 0.5*(Z{p}+Z{p}');
end
end
end
if (isemptyAtb)
X = X(1:end-1); Z = Z(1:end-1);
end
%%*****************************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
HSDsortA.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/HSDSolver/HSDsortA.m
| 2,577 |
utf_8
|
0a74ddbb8a0c79bf22592d780d865e06
|
%%*********************************************************************
%% sortA: sort columns of At{p} in ascending order according to the
%% number of nonzero elements.
%%
%% [At,C,b,X0,Z0,permA,permZ] = sortA(blk,At,C,b,X0,Z0);
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%*********************************************************************
function [At,C,Cnew,X0,Z0,permA,invpermA,permZ] = HSDsortA(blk,At,C,Cnew,b,X0,Z0)
global spdensity smallblkdim
%%
numblk = size(blk,1);
m = length(b);
nnzA = zeros(numblk,m);
permA = kron(ones(numblk,1),1:m);
invpermA = kron(ones(numblk,1),1:m);
permZ = cell(size(blk,1),1);
%%
for p=1:size(blk,1)
pblk = blk(p,:);
n = sum(pblk{2});
if strcmp(pblk{1},'s') && (max(pblk{2}) > smallblkdim)
n22 = sum(pblk{2}.*(pblk{2}+1))/2;
m1 = size(At{p,1},2);
if (length(pblk{2}) == 1)
tmp = abs(C{p}) + abs(Z0{p});
if (~isempty(At{p,1}))
tmp = tmp + smat(blk(p,:),abs(At{p,1})*ones(m1,1),1);
end
if (nnz(tmp) < spdensity*n22);
per = symamd(tmp);
invper = zeros(n,1); invper(per) = 1:n;
permZ{p} = invper;
if (~isempty(At{p,1}))
isspAt = issparse(At{p,1});
for k = 1:m1
Ak = smat(pblk,At{p,1}(:,k),1);
At{p,1}(:,k) = svec(pblk,Ak(per,per),isspAt);
end
end
C{p} = C{p}(per,per);
Z0{p} = Z0{p}(per,per);
X0{p} = X0{p}(per,per);
Cnew{p} = Cnew{p}(per,per);
else
per = [];
end
if (length(pblk) > 2) && (~isempty(per))
P = spconvert([(1:n)', per', ones(n,1)]);
At{p,2} = P*At{p,2};
end
end
if ~isempty(At{p,1}) && (mexnnz(At{p,1}) < m*n22/2)
for k = 1:m1
Ak = At{p,1}(:,k);
nnzA(p,k) = length(find(abs(Ak) > eps));
end
[dummy,permAp] = sort(nnzA(p,1:m1)); %#ok
At{p,1} = At{p,1}(:,permAp);
permA(p,1:m1) = permAp;
invpermA(p,permAp) = 1:m1;
end
elseif strcmp(pblk{1},'q') || strcmp(pblk{1},'l') || strcmp(pblk{1},'u');
if ~issparse(At{p,1});
At{p,1} = sparse(At{p,1});
end
end
end
%%*********************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
HSDHKMrhsfun.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/HSDSolver/HSDHKMrhsfun.m
| 2,666 |
utf_8
|
16409ae4672f80ef54a33c31ef30000f
|
%%*******************************************************************
%% HSDHKMrhsfun: compute the right-hand side vector of the
%% Schur complement equation for the HKM direction.
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%*******************************************************************
function [rhs,EinvRc,hRd] = HSDHKMrhsfun(blk,At,par,X,Z,rp,Rd,sigmu,hRd,dX,dZ)
m = par.m;
if (nargin > 8)
corrector = 1;
else
corrector = 0;
hRd = zeros(m+2,1);
end
hEinvRc = zeros(m+2,1);
EinvRc = cell(size(blk,1),1);
if length(sigmu)==1; sigmu = sigmu*ones(1,size(blk,1)); end
%%
for p = 1:size(blk,1)
pblk = blk(p,:);
n = sum(pblk{2});
if strcmp(pblk{1},'l')
if (corrector)
Rq = dX{p}.*dZ{p};
else
Rq = sparse(n,1);
tmp = par.dd{p}.*Rd{p};
tmp2 = mexMatvec(At{p},tmp,1);
hRd = hRd + tmp2;
end
EinvRc{p} = sigmu(p)./Z{p}-X{p} -Rq./Z{p};
tmp2 = mexMatvec(At{p,1},EinvRc{p},1);
hEinvRc = hEinvRc + tmp2;
elseif strcmp(pblk{1},'q')
if (corrector)
ff{p} = qops(pblk,1./par.gamz{p},Z{p},3); %#ok
hdx = qops(pblk,par.gamz{p},ff{p},5,dX{p});
hdz = qops(pblk,par.gamz{p},ff{p},6,dZ{p});
hdxdz = Arrow(pblk,hdx,hdz);
Rq = qops(pblk,par.gamz{p},ff{p},6,hdxdz);
else
Rq = sparse(n,1);
tmp = par.dd{p}.*Rd{p} ...
+ qops(pblk,qops(pblk,Rd{p},par.Zinv{p},1),X{p},3) ...
+ qops(pblk,qops(pblk,Rd{p},X{p},1),par.Zinv{p},3);
tmp2 = mexMatvec(At{p,1},tmp,1);
hRd = hRd + tmp2;
end
EinvRc{p} = sigmu(p)*par.Zinv{p}-X{p} -Rq;
tmp2 = mexMatvec(At{p,1},EinvRc{p},1);
hEinvRc = hEinvRc + tmp2;
elseif strcmp(pblk{1},'s')
if (corrector)
Rq = Prod3(pblk,dX{p},dZ{p},par.Zinv{p},0);
Rq = 0.5*(Rq+Rq');
else
Rq = sparse(n,n);
tmp = Prod3(pblk,X{p},Rd{p},par.Zinv{p},0,par.nzlistAy{p});
EinvRc{p} = 0.5*(tmp+tmp');
tmp2 = AXfun(pblk,At(p,:),par.permA(p,:),EinvRc(p));
hRd = hRd + tmp2;
end
EinvRc{p} = sigmu(p)*par.Zinv{p}-X{p}- Rq;
tmp2 = AXfun(pblk,At(p,:),par.permA(p,:),EinvRc(p));
hEinvRc = hEinvRc + tmp2;
end
end
%%
rhs = rp + hRd - hEinvRc;
rhs(m+1) = rhs(m+1) + (par.mu/par.tau - par.kap);
if (corrector)
rhs(m+1) = rhs(m+1) - par.dtau*par.dkap/par.tau;
end
%%*******************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
HSDsqlpcheckconvg.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/HSDSolver/HSDsqlpcheckconvg.m
| 6,249 |
utf_8
|
a579e4972fd77d5cc3e11b72bf56d3a9
|
%%*****************************************************************************
%% HSDsqlpcheckconvg: check convergence.
%%
%% ZpATynorm, AX, normX, normZ are with respect to the
%% original variables, not the HSD variables.
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%*****************************************************************************
function [param,breakyes,use_olditer,msg] = HSDsqlpcheckconvg(param,runhist)
termcode = param.termcode;
iter = param.iter;
obj = param.obj;
relgap = param.relgap;
gap = param.gap;
prim_infeas = param.prim_infeas;
dual_infeas = param.dual_infeas;
mu = param.mu;
prim_infeas_bad = param.prim_infeas_bad;
dual_infeas_bad = param.dual_infeas_bad;
printlevel = param.printlevel;
stoplevel = param.stoplevel;
inftol = param.inftol;
gaptol = param.gaptol;
kap = param.kap;
tau = param.tau;
theta = param.theta;
breakyes = 0;
use_olditer = 0;
msg = [];
infeas = max(prim_infeas,dual_infeas);
prim_infeas_min = min(param.prim_infeas_min, max(prim_infeas,1e-10));
dual_infeas_min = min(param.dual_infeas_min, max(dual_infeas,1e-10));
%%
err = max(infeas,relgap);
if (obj(2) > 0); homRd = param.ZpATynorm/obj(2); else homRd = inf; end
if (obj(1) < 0); homrp = norm(param.AX)/(-obj(1)); else homrp = inf; end
if (param.normX > 1e15*param.normX0 || param.normZ > 1e15*param.normZ0)
termcode = 3;
breakyes = 1;
end
if (homRd < min(1e-6,1e-2*sqrt(err*inftol)) && tau < 1e-4 ...
&& prim_infeas > 0.5*runhist.pinfeas(iter)) ...
|| (homRd < 10*tau && tau < 1e-7)
termcode = 1;
breakyes = 1;
end
if (homrp < min(1e-6,1e-2*sqrt(err*inftol)) && tau < 1e-4 ...
&& dual_infeas > 0.5*runhist.dinfeas(iter)) ...
|| (homrp < 10*tau && tau < 1e-7)
termcode = 2;
breakyes = 1;
end
if (err < gaptol)
msg = sprintf('Stop: max(relative gap,infeasibilities) < %3.2e',gaptol);
if (printlevel); fprintf('\n %s',msg); end
termcode = 0;
breakyes = 1;
end
min_prim_infeas = min(runhist.pinfeas(1:iter));
prim_infeas_bad = prim_infeas_bad + (prim_infeas > ...
max(1e-10,5*min_prim_infeas) && (min_prim_infeas < 1e-2));
if (mu < 1e-6)
idx = max(1,iter-1): iter;
elseif (mu < 1e-3);
idx = max(1,iter-2): iter;
else
idx = max(1,iter-3): iter;
end
idx2 = max(1,iter-4): iter;
gap_ratio2 = runhist.gap(idx2+1)./runhist.gap(idx2);
gap_slowrate = min(0.8,max(0.6,2*mean(gap_ratio2)));
gap_ratio = runhist.gap(idx+1)./runhist.gap(idx);
pstep = runhist.step(iter+1);
if (infeas < 1e-4 || prim_infeas_bad) && (relgap < 1e-3) ...
&& (iter > 5) && (prim_infeas > (1-pstep/2)*runhist.pinfeas(iter))
gap_slow = all(gap_ratio > gap_slowrate) && (relgap < 1e-3);
min_pinfeas = min(runhist.pinfeas);
if (relgap < 0.1*infeas) ...
&& ((runhist.step(iter+1) < 0.5) || (min_pinfeas < min(1e-6,0.1*prim_infeas))) ...
&& (dual_infeas > 0.9*runhist.dinfeas(iter) || (dual_infeas < 1e-2*gaptol))
msg = 'Stop: relative gap < infeasibility';
if (printlevel); fprintf('\n %s',msg); end
termcode = -1;
breakyes = 1;
elseif (gap_slow) && (infeas > 0.9*runhist.infeas(iter)) ...
&& (theta < 1e-8)
msg = 'Stop: progress is too slow';
if (printlevel); fprintf('\n %s',msg); end
termcode = -5;
breakyes = 1;
end
elseif (prim_infeas_bad) && (iter >50) && all(gap_ratio > gap_slowrate)
msg = 'Stop: progress is bad';
if (printlevel); fprintf('\n %s',msg); end
termcode = -5;
breakyes = 1;
elseif (infeas < 1e-8) && (gap > 1.2*mean(runhist.gap(idx)))
msg = 'Stop: progress is bad*';
if (printlevel); fprintf('\n %s',msg); end
termcode = -5;
breakyes = 1;
end
if (err < 1e-3) && (iter > 10) ...
&& (runhist.pinfeas(iter+1) > 0.9*runhist.pinfeas(max(1,iter-5))) ...
&& (runhist.dinfeas(iter+1) > 0.9*runhist.dinfeas(max(1,iter-5))) ...
&& (runhist.relgap(iter+1) > 0.1*runhist.relgap(max(1,iter-5)));
msg = 'Stop: progress is bad**';
if (printlevel); fprintf('\n %s',msg); end
termcode = -5;
breakyes = 1;
end
if (infeas > 100*max(1e-12,min(runhist.infeas)) && relgap < 1e-4)
msg = 'Stop: infeas has deteriorated too much';
if (printlevel); fprintf('\n %s, %3.1e',msg,infeas); end
use_olditer = 1;
termcode = -7;
breakyes = 1;
end
if (min(runhist.infeas) < 1e-4 || prim_infeas_bad) ...
&& (max(runhist.infeas) > 1e-4) && (iter > 5)
relgap2 = abs(diff(obj))/(1+mean(abs(obj)));
if (relgap2 < 1e-3);
step_short = all(runhist.step(iter:iter+1) < 0.1) ;
elseif (relgap2 < 1)
idx = max(1,iter-3): iter+1;
step_short = all(runhist.step(idx) < 0.05);
else
step_short = 0;
end
if (step_short)
msg = 'Stop: steps too short consecutively';
if (printlevel); fprintf('\n %s',msg); end
termcode = -5;
breakyes = 1;
end
end
if (iter > 3 && iter < 20) && (max(runhist.step(max(1,iter-3):iter+1)) < 1e-3) ...
&& (infeas > 1) && (min(homrp,homRd) > 1000*inftol)
if (stoplevel >= 2)
msg = 'Stop: steps too short consecutively';
if (printlevel); fprintf('\n %s',msg); end
termcode = -5;
breakyes = 1;
end
end
if (pstep < 1e-4) && (err > 1.1*max(runhist.relgap(iter),runhist.infeas(iter)))
msg = 'Stop: steps are too short';
if (printlevel); fprintf('\n %s',msg); end
use_olditer = 1;
termcode = -5;
breakyes = 1;
end
if (iter == param.maxit)
termcode = -6;
msg = 'Stop: maximum number of iterations reached';
if (printlevel); fprintf('\n %s',msg); end
end
if (infeas < 1e-8 && relgap < 1e-10 && kap < 1e-13 && theta < 1e-15)
msg = 'Stop: obtained accurate solution';
if (printlevel); fprintf('\n %s',msg); end
termcode = 0;
breakyes = 1;
end
param.prim_infeas_bad = prim_infeas_bad;
param.prim_infeas_min = prim_infeas_min;
param.dual_infeas_bad = dual_infeas_bad;
param.dual_infeas_min = dual_infeas_min;
param.termcode = termcode;
%%*****************************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
HSDNTdirfun.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/HSDSolver/HSDNTdirfun.m
| 1,459 |
utf_8
|
a045827a3ca1adcf8806cfd8234ad5e4
|
%%*******************************************************************
%% HSDNTdirfun: compute (dX,dZ), given dy, for the NT direction.
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%*******************************************************************
function [par,dX,dy,dZ] = HSDNTdirfun(blk,At,par,Rd,EinvRc,xx)
global solve_ok
dX = cell(size(blk,1),1); dZ = cell(size(blk,1),1); dy = [];
if (any(isnan(xx)) || any(isinf(xx)))
solve_ok = 0;
fprintf('\n HSDNTdirfun: solution contains NaN or inf.');
return;
end
%%
m = par.m;
dy2 = xx(1:m+2);
%%
for p=1:size(blk,1)
pblk = blk(p,:);
if strcmp(pblk{1},'l')
dZ(p) = ops(Rd(p),'-',Atyfun(pblk,At(p,:),[],[],dy2));
tmp = par.dd{p}.*dZ{p};
dX{p} = EinvRc{p} - tmp;
elseif strcmp(pblk{1},'q')
dZ(p) = ops(Rd(p),'-',Atyfun(pblk,At(p,:),[],[],dy2));
tmp = par.dd{p}.*dZ{p} + qops(pblk,qops(pblk,dZ{p},par.ee{p},1),par.ee{p},3);
dX{p} = EinvRc{p} - tmp;
elseif strcmp(pblk{1},'s')
dZ(p) = ops(Rd(p),'-',Atyfun(pblk,At(p,:),par.permA(p,:),par.isspAy(p),dy2));
tmp = Prod3(pblk,par.W{p},dZ{p},par.W{p},1);
dX{p} = EinvRc{p}-tmp;
end
end
dy = dy2(1:m);
par.dtau = dy2(m+1);
par.dtheta = dy2(m+2);
par.dkap = (par.mu./par.tau - par.kap) - par.kap*(par.dtau/par.tau);
%%*******************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
HSDNTrhsfun.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/HSDSolver/HSDNTrhsfun.m
| 3,424 |
utf_8
|
02348c55d691a53b023639b8103757be
|
%%*******************************************************************
%% HSDNTrhsfun: compute the right-hand side vector of the
%% Schur complement equation for the NT direction.
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%*******************************************************************
function [rhs,EinvRc,hRd] = HSDNTrhsfun(blk,At,par,X,Z,rp,Rd,sigmu,hRd,dX,dZ)
global spdensity
m = par.m;
if (nargin > 8)
corrector = 1;
else
corrector = 0;
hRd = zeros(m+2,1);
end
hEinvRc = zeros(m+2,1);
EinvRc = cell(size(blk,1),1);
if length(sigmu)==1; sigmu = sigmu*ones(1,size(blk,1)); end
%%
for p = 1:size(blk,1)
pblk = blk(p,:);
n = sum(pblk{2}); numblk = length(pblk{2});
if strcmp(pblk{1},'l')
if (corrector)
Rq = dX{p}.*dZ{p};
else
Rq = sparse(n,1);
tmp = par.dd{p}.*Rd{p};
tmp2 = mexMatvec(At{p},tmp,1);
hRd = hRd + tmp2;
end
EinvRc{p} = sigmu(p)./Z{p}-X{p} -Rq./Z{p};
tmp2 = mexMatvec(At{p},EinvRc{p},1);
hEinvRc = hEinvRc + tmp2;
elseif strcmp(pblk{1},'q')
w = sqrt(par.gamz{p}./par.gamx{p});
if (corrector)
hdx = qops(pblk,w,par.ff{p},5,dX{p});
hdz = qops(pblk,w,par.ff{p},6,dZ{p});
hdxdz = Arrow(pblk,hdx,hdz);
vv = qops(pblk,w,par.ff{p},5,X{p});
Vihdxdz = Arrow(pblk,vv,hdxdz,1);
Rq = qops(pblk,w,par.ff{p},6,Vihdxdz);
else
Rq = sparse(n,1);
tmp = par.dd{p}.*Rd{p} + qops(pblk,qops(pblk,Rd{p},par.ee{p},1),par.ee{p},3);
tmp2 = mexMatvec(At{p},tmp,1);
hRd = hRd + tmp2;
end
EinvRc{p} = qops(pblk,-sigmu(p)./(par.gamz{p}.*par.gamz{p}),Z{p},4)-X{p}-Rq;
tmp2 = mexMatvec(At{p},EinvRc{p},1);
hEinvRc = hEinvRc + tmp2;
elseif strcmp(pblk{1},'s')
n2 = pblk{2}.*(pblk{2}+1)/2;
if (corrector)
hdZ = Prod3(pblk,par.G{p},dZ{p},par.G{p}',1);
hdX = spdiags(-par.sv{p},0,n,n)-hdZ;
tmp = Prod2(pblk,hdX,hdZ,0);
tmp = 0.5*(tmp+tmp');
if (numblk == 1)
d = par.sv{p};
e = ones(pblk{2},1);
Rq = 2*tmp./(d*e'+e*d');
if (nnz(Rq) <= spdensity*n2); Rq = sparse(Rq); end
else
Rq = sparse(n,n);
s = [0, cumsum(pblk{2})];
for i = 1:numblk
pos = s(i)+1 : s(i+1);
d = par.sv{p}(pos); e = ones(length(pos),1);
Rq(pos,pos) = 2*tmp(pos,pos)./(d*e' + e*d'); %#ok
end
end
else
Rq = sparse(n,n);
EinvRc{p} = Prod3(pblk,par.W{p},Rd{p},par.W{p},1,par.nzlistAy{p});
tmp2 = AXfun(pblk,At(p,:),par.permA(p,:),EinvRc(p));
hRd = hRd + tmp2;
end
tmp = spdiags(sigmu(p)./par.sv{p} -par.sv{p},0,n,n);
EinvRc{p} = Prod3(pblk,par.G{p}',tmp-Rq,par.G{p},1);
tmp2 = AXfun(pblk,At(p,:),par.permA(p,:),EinvRc(p));
hEinvRc = hEinvRc + tmp2;
end
end
%%
rhs = rp + hRd - hEinvRc;
rhs(m+1) = rhs(m+1) + (par.mu/par.tau - par.kap);
if (corrector)
rhs(m+1) = rhs(m+1) - par.dtau*par.dkap/par.tau;
end
%%*******************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
HSDHKMpred.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/HSDSolver/HSDHKMpred.m
| 2,644 |
utf_8
|
81b89c36e0d0bad30836c551264a6a05
|
%%*******************************************************************
%% HSDHKMpred: Compute (dX,dy,dZ) for the H..K..M direction.
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%*******************************************************************
function [par,dX,dy,dZ,coeff,L,hRd] = ...
HSDHKMpred(blk,At,par,rp,Rd,sigmu,X,Z,invZchol)
global schurfun schurfun_par
%%
%% compute HKM scaling
%%
Zinv = cell(size(blk,1),1); dd = cell(size(blk,1),1);
gamx = cell(size(blk,1),1); gamz = cell(size(blk,1),1);
for p = 1:size(blk,1)
pblk = blk(p,:);
n = sum(pblk{2});
numblk = length(pblk{2});
if strcmp(pblk{1},'l')
Zinv{p} = 1./Z{p};
dd{p} = X{p}./Z{p};
elseif strcmp(pblk{1},'q')
gaptmp = qops(pblk,X{p},Z{p},1);
gamz2 = qops(pblk,Z{p},Z{p},2);
gamz{p} = sqrt(gamz2);
Zinv{p} = qops(pblk,-1./gamz2,Z{p},4);
dd{p} = qops(pblk,gaptmp./gamz2,ones(n,1),4);
elseif strcmp(pblk{1},'s')
if (numblk == 1)
Zinv{p} = Prod2(pblk,full(invZchol{p}),invZchol{p}',1);
else
Zinv{p} = Prod2(pblk,invZchol{p},invZchol{p}',1);
end
end
end
par.Zinv = Zinv; par.gamx = gamx; par.gamz = gamz; par.dd = dd;
%%
%% compute schur matrix
%%
m = par.m;
schur = sparse(m+2,m+2);
UU = []; EE = [];
%%
for p = 1:size(blk,1)
pblk = blk(p,:);
if strcmp(pblk{1},'l')
[schur,UU,EE] = schurmat_lblk(blk,At,par,schur,UU,EE,p,par.dd);
elseif strcmp(pblk{1},'q');
[schur,UU,EE] = schurmat_qblk(blk,At,par,schur,UU,EE,p,par.dd,par.Zinv,X);
elseif strcmp(pblk{1},'s')
if isempty(schurfun{p})
schur = schurmat_sblk(blk,At,par,schur,p,X,par.Zinv);
elseif ischar(schurfun{p})
if ~isempty(par.permZ{p})
Zpinv = Zinv{p}(par.permZ{p},par.permZ{p});
Xp = X{p}(par.permZ{p},par.permZ{p});
else
Xp = X{p};
Zpinv = Zinv{p};
end
schurtmp = feval( schurfun{p}, Xp,Zpinv,schurfun_par(p,:));
schur = schur + schurtmp;
end
end
end
%%
%% compute rhs
%%
[rhs,EinvRc,hRd] = HSDHKMrhsfun(blk,At,par,X,Z,rp,Rd,sigmu);
%%
%% solve linear system
%%
par.addschur = par.kap/par.tau;
schur(m+1,m+1) = schur(m+1,m+1) + par.kap/par.tau;
schur(m+2,m+2) = schur(m+2,m+2) + par.addschur;
[xx,coeff,L] = HSDlinsysolve(par,schur,UU,EE,par.Umat,rhs);
%%
%% compute (dX,dZ)
%%
[par,dX,dy,dZ] = HSDHKMdirfun(blk,At,par,Rd,EinvRc,X,xx);
%%*******************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
HSDsqlpmain.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/HSDSolver/HSDsqlpmain.m
| 28,301 |
utf_8
|
df880652075e1e6d94eefd6ddfe38c64
|
%%*****************************************************************************
%% HSDsqlp: solve an semidefinite-quadratic-linear program
%% by infeasible path-following method on the homogeneous self-dual model.
%%
%% [obj,X,y,Z,info,runhist] =
%% HSDsqlp(blk,At,C,b,OPTIONS,X0,y0,Z0,kap0,tau0,theta0);
%%
%% Input:
%% blk : a cell array describing the block diagonal structure of SQL data.
%% At : a cell array with At{p} = [svec(Ap1) ... svec(Apm)]
%% b,C : data for the SQL instance.
%% OPTIONS: a structure that specifies parameters required in HSDsqlp.m,
%% (if it is not given, the default in sqlparameters.m is used).
%%
%% (X0,y0,Z0): an initial iterate (if it is not given, the default is used).
%% (kap0,tau0,theta0): initial parameters (if not given, the default is used).
%%
%% Output: obj = [<C,X> <b,y>].
%% (X,y,Z): an approximately optimal solution or a primal or dual
%% infeasibility certificate.
%% info.termcode = termination-code
%% info.iter = number of iterations
%% info.obj = [primal-obj, dual-obj]
%% info.cputime = total-time
%% info.gap = gap
%% info.pinfeas = primal_infeas
%% info.dinfeas = dual_infeas
%% runhist.pobj = history of primal objective value.
%% runhist.dobj = history of dual objective value.
%% runhist.gap = history of <X,Z>.
%% runhist.pinfeas = history of primal infeasibility.
%% runhist.dinfeas = history of dual infeasibility.
%% runhist.cputime = history of cputime spent.
%%----------------------------------------------------------------------------
%% The OPTIONS structure specifies the required parameters:
%% vers gam predcorr expon gaptol inftol steptol
%% maxit printlevel ...
%% (all have default values set in sqlparameters.m).
%%
%%*************************************************************************
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%*************************************************************************
function [obj,X,y,Z,info,runhist] = ...
HSDsqlpmain(blk,At,C,b,par,X0,y0,Z0,kap0,tau0,theta0)
%%
%%-----------------------------------------
%% get parameters from the OPTIONS structure.
%%-----------------------------------------
%%
global spdensity smallblkdim solve_ok use_LU
global schurfun schurfun_par
% matlabversion = par.matlabversion;
isoctave = exist( 'OCTAVE_VERSION', 'builtin' );
if isoctave,
w1 = warning('off','Octave:nearly-singular-matrix');
else
w1 = warning('off','MATLAB:nearlySingularMatrix');
w2 = warning('off','MATLAB:singularMatrix');
end
vers = par.vers;
predcorr = par.predcorr;
gam = par.gam;
expon = par.expon;
gaptol = par.gaptol;
inftol = par.inftol;
steptol = par.steptol;
maxit = par.maxit;
printlevel = par.printlevel;
stoplevel = par.stoplevel;
% scale_data = par.scale_data;
spdensity = par.spdensity;
rmdepconstr = par.rmdepconstr;
smallblkdim = par.smallblkdim;
schurfun = par.schurfun;
schurfun_par = par.schurfun_par;
% ublksize = par.ublksize;
%%
tstart = clock;
X = X0; y = y0; Z = Z0;
for p = 1:size(blk,1)
if strcmp(blk{p,1},'u'); Z{p} = zeros(blk{p,2},1); end
end
%%
%%-----------------------------------------
%% convert unrestricted blk to linear blk.
%%-----------------------------------------
%%
ublkidx = zeros(size(blk,1),1);
Cpert = zeros(size(blk,1),1);
Cnew = C;
perturb_C = 1;
for p = 1:size(blk,1)
pblk = blk(p,:);
n = sum(pblk{2});
tmp = max(1,norm(C{p},'fro'))/sqrt(n);
if strcmp(pblk{1},'s')
if (perturb_C); Cpert(p) = 1e-3*tmp; end
Cnew{p} = C{p} + Cpert(p)*speye(n);
elseif strcmp(pblk{1},'q')
if (perturb_C); Cpert(p) = 0*tmp; end; %% old: 1e-3
s = 1+[0, cumsum(pblk{2})];
tmp2 = zeros(n,1); len = length(pblk{2});
tmp2(s(1:len)) = ones(len,1);
Cnew{p} = C{p} + Cpert(p)*tmp2;
elseif strcmp(pblk{1},'l')
if (perturb_C); Cpert(p) = 1e-4*tmp; end; %% old: 1e-3
Cnew{p} = C{p} + Cpert(p)*ones(n,1);
elseif strcmp(pblk{1},'u')
msg = sprintf('convert ublk to linear blk');
if (printlevel); fprintf('\n *** %s',msg); end
ublkidx(p) = 1;
n = 2*pblk{2};
blk{p,1} = 'l'; blk{p,2} = n;
if (perturb_C); Cpert(p) = 1e-2*tmp; end
C{p} = [C{p}; -C{p}];
At{p} = [At{p}; -At{p}];
Cnew{p} = C{p} + Cpert(p)*ones(n,1);
X{p} = 1+randmat(n,1,0,'u');
Z{p} = 1+randmat(n,1,0,'u');
end
end
%%
%%-----------------------------------------
%% check if the matrices Ak are
%% linearly independent.
%%-----------------------------------------
%%
m0 = length(b);
[At,b,y,indeprows,depconstr,feasible,AAt] = ...
checkdepconstr(blk,At,b,y,rmdepconstr);
if (~feasible)
msg = 'SQLP is not feasible';
if (printlevel); fprintf('\n %s',msg); end
return;
end
par.depconstr = depconstr;
%%
normb = 1+max(abs(b));
normC = zeros(length(C),1);
for p = 1:length(C); normC(p) = max(max(abs(C{p}))); end
normC = 1+max(normC);
nn = ops(C,'getM');
m = length(b);
if (nargin <= 8) || (isempty(kap0) || isempty(tau0) || isempty(theta0))
if (max([ops(At,'norm'),ops(C,'norm'),norm(b)]) > 1e6)
kap0 = 10*blktrace(blk,X,Z);
else
kap0 = blktrace(blk,X,Z);
end
tau0 = 1; theta0 = 1;
end
kap = kap0; tau = tau0; theta = theta0;
%%
normX0 = ops(X0,'norm')/tau; normZ0 = ops(Z0,'norm')/tau;
bbar = (tau*b-AXfun(blk,At,[],X))/theta;
ZpATy = ops(Z,'+',Atyfun(blk,At,[],[],y));
Cbar = ops(ops(ops(tau,'*',C),'-',ZpATy),'/',theta);
gbar = (blktrace(blk,C,X)-b'*y+kap)/theta;
abar = (blktrace(blk,X,Z)+tau*kap)/theta;
for p = 1:size(blk,1);
pblk = blk(p,:);
if strcmp(pblk{1},'s')
At{p} = [At{p}, -svec(pblk,Cnew{p},1), svec(pblk,Cbar{p},1)];
else
At{p} = [At{p}, -Cnew{p}, Cbar{p}];
end
end
Bmat = [sparse(m,m), -b, bbar; b', 0, gbar; -bbar', -gbar, 0];
em1 = zeros(m+2,1); em1(m+1) = 1;
em2 = zeros(m+2,1); em2(m+2) = 1;
par.Umat = [[b;0;0], [bbar;gbar;0], em1, em2];
par.m = m;
par.diagAAt = [full(diag(AAt)); 1; 1];
%%
%%-----------------------------------------
%% find the combined list of non-zero
%% elements of Aj, j = 1:k, for each k.
%%-----------------------------------------
%%
par.numcolAt = length(b)+2;
[At,C,Cnew,X,Z,par.permA,par.invpermA,par.permZ] = ...
HSDsortA(blk,At,C,Cnew,[b;0;0],X,Z); %#ok
[par.isspA,par.nzlistA,par.nzlistAsum,par.isspAy,par.nzlistAy] = ...
nzlist(blk,At,par);
%%
%%-----------------------------------------
%% initialization
%%-----------------------------------------
%%
y2 = [y; tau; theta];
AX = AXfun(blk,At,par.permA,X);
rp = [zeros(m,1); kap; -abar] - AX - Bmat*y2;
% Rd = ops(Atyfun(blk,At,par.permA,par.isspAy,-y2),'-',Z);
trXZ = blktrace(blk,X,Z);
mu = (trXZ+kap*tau)/(nn+1);
obj = [blktrace(blk,C,X), b'*y]/tau;
gap = trXZ/tau^2;
relgap = gap/(1+mean(abs(obj)));
ZpATy = ops(Z,'+',Atyfun(blk,At,par.permA,par.isspAy,[y;0;0]));
ZpATynorm = ops(ZpATy,'norm');
prim_infeas = norm(b - AX(1:m)/tau)/normb;
dual_infeas = ops(ops(C,'-',ops(ZpATy,'/',tau)),'norm')/normC;
infeas = max(prim_infeas,dual_infeas);
%%
termcode = 0;
pstep = 1; dstep = 1; pred_convg_rate = 1; corr_convg_rate = 1;
besttol = max( relgap, infeas );
% homRd = inf; homrp = inf; dy = zeros(length(b),1);
msg = []; msg2 = [];
runhist.pobj = obj(1);
runhist.dobj = obj(2);
runhist.gap = gap;
runhist.relgap = relgap;
runhist.pinfeas = prim_infeas;
runhist.dinfeas = dual_infeas;
runhist.infeas = infeas;
runhist.cputime = etime(clock,tstart);
runhist.step = 0;
runhist.kappa = kap;
runhist.tau = tau;
runhist.theta = theta;
runhist.useLU = 0;
ttime.preproc = runhist.cputime;
ttime.pred = 0; ttime.pred_pstep = 0; ttime.pred_dstep = 0;
ttime.corr = 0; ttime.corr_pstep = 0; ttime.corr_dstep = 0;
ttime.pchol = 0; ttime.dchol = 0; ttime.misc = 0;
%%
%%-----------------------------------------
%% display parameters, and initial info
%%-----------------------------------------
%%
if (printlevel >= 2)
fprintf('\n********************************************');
fprintf('************************************************\n');
fprintf(' SDPT3: homogeneous self-dual path-following algorithms');
fprintf('\n********************************************');
fprintf('************************************************\n');
[hh,mm,ss] = mytime(ttime.preproc);
if (printlevel>=3)
fprintf(' version predcorr gam expon\n');
if (vers == 1); fprintf(' HKM '); elseif (vers == 2); fprintf(' NT '); end
fprintf(' %1.0f %4.3f %1.0f\n',predcorr,gam,expon);
fprintf('it pstep dstep pinfeas dinfeas gap')
fprintf(' mean(obj) cputime kap tau theta\n');
fprintf('------------------------------------------------');
fprintf('--------------------------------------------\n');
fprintf('%2.0f|%4.3f|%4.3f|%2.1e|%2.1e|',0,0,0,prim_infeas,dual_infeas);
fprintf('%2.1e|%- 7.6e| %s:%s:%s|',gap,mean(obj),hh,mm,ss);
fprintf('%2.1e|%2.1e|%2.1e|',kap,tau,theta);
end
end
%%
%%---------------------------------------------------------------
%% start main loop
%%---------------------------------------------------------------
%%
EE = ops(blk,'identity');
normE = ops(EE,'norm');
Zpertold = 1;
[Xchol,indef(1)] = blkcholfun(blk,X);
[Zchol,indef(2)] = blkcholfun(blk,Z);
if any(indef)
msg = 'stop: X, Z are not both positive definite';
if (printlevel); fprintf('\n %s\n',msg); end
info.termcode = -3;
info.msg1 = msg;
return;
end
%%
param.termcode = termcode;
param.iter = 0;
param.normX0 = normX0;
param.normZ0 = normZ0;
param.m0 = m0;
param.indeprows = indeprows;
param.prim_infeas_bad = 0;
param.dual_infeas_bad = 0;
param.prim_infeas_min = prim_infeas;
param.dual_infeas_min = dual_infeas;
param.gaptol = gaptol;
param.inftol = inftol;
param.maxit = maxit;
param.printlevel = printlevel;
param.stoplevel = stoplevel;
breakyes = 0;
dy = zeros(length(b),1); dtau = 0; dtheta = 0;
Xbest = X; ybest = y; Zbest = Z;
% kapbest = kap; taubest = tau; thetabest = theta;
%%
for iter = 1:maxit;
update_iter = 0; pred_slow = 0; corr_slow = 0; % step_short = 0;
tstart = clock;
timeold = tstart;
par.kap = kap;
par.tau = tau;
par.theta = theta;
par.mu = mu;
par.iter = iter;
par.y = y;
par.dy2 = [dy; dtau; dtheta];
par.rp = rp;
par.ZpATynorm = ZpATynorm;
%%
%%--------------------------------------------------
%% perturb C
%%--------------------------------------------------
%%
if (perturb_C)
[At,Cpert] = HSDsqlpCpert(blk,At,par,C,X,Cpert,runhist);
maxCpert(iter) = max(Cpert); %#ok
%%fprintf(' %2.1e',max(Cpert));
if (iter > 10 && norm(diff(maxCpert([iter-3,iter]))) < 1e-13)
Cpert = 0.5*Cpert;
maxCpert(iter) = max(Cpert); %#ok
end
AX = AXfun(blk,At,par.permA,X);
rp = [zeros(m,1); kap; -abar] - AX - Bmat*y2;
Rd = ops(Atyfun(blk,At,par.permA,par.isspAy,-y2),'-',Z);
end
%%---------------------------------------------------------------
%% predictor step.
%%---------------------------------------------------------------
%%
if (predcorr)
sigma = 0;
else
sigma = 1-0.9*min(pstep,dstep);
if (iter == 1); sigma = 0.5; end;
end
sigmu = sigma*mu;
invXchol = cell(size(blk,1),1);
invZchol = ops(Zchol,'inv');
if (vers == 1);
[par,dX,dy,dZ,coeff,L,hRd] = ...
HSDHKMpred(blk,At,par,rp,Rd,sigmu,X,Z,invZchol);
elseif (vers == 2);
[par,dX,dy,dZ,coeff,L,hRd] = ...
HSDNTpred(blk,At,par,rp,Rd,sigmu,X,Z,Zchol,invZchol);
end
if (solve_ok <= 0)
msg = 'stop: difficulty in computing predictor directions';
if (printlevel); fprintf('\n %s',msg); end
runhist.cputime(iter+1) = etime(clock,tstart);
termcode = -4;
break;
end
timenew = clock;
ttime.pred = ttime.pred + etime(timenew,timeold); timeold=timenew;
%%
%%-----------------------------------------
%% step-lengths for predictor step
%%-----------------------------------------
%%
if (gam == 0)
gamused = 0.9 + 0.09*min(pstep,dstep);
else
gamused = gam;
end
kapstep = max( (par.dkap<0)*(-kap/(par.dkap-eps)), (par.dkap>=0)*1e6 );
taustep = max( (par.dtau<0)*(-tau/(par.dtau-eps)), (par.dtau>=0)*1e6 );
[Xstep,invXchol] = steplength(blk,X,dX,Xchol,invXchol);
timenew = clock;
ttime.pred_pstep = ttime.pred_pstep + etime(timenew,timeold); timeold=timenew;
Zstep = steplength(blk,Z,dZ,Zchol,invZchol);
pstep = min(1,gamused*min([Xstep,Zstep,kapstep,taustep]));
dstep = pstep;
kappred = kap + pstep*par.dkap;
taupred = tau + pstep*par.dtau;
trXZpred = trXZ + pstep*blktrace(blk,dX,Z) + dstep*blktrace(blk,X,dZ) ...
+ pstep*dstep*blktrace(blk,dX,dZ);
mupred = (trXZpred + kappred*taupred)/(nn+1);
mupredhist(iter) = mupred; %#ok
timenew = clock;
ttime.pred_dstep = ttime.pred_dstep + etime(timenew,timeold); timeold=timenew;
%%
%%-----------------------------------------
%% stopping criteria for predictor step.
%%-----------------------------------------
%%
if (min(pstep,dstep) < steptol) && (stoplevel)
msg = 'stop: steps in predictor too short';
if (printlevel)
fprintf('\n %s',msg);
fprintf(': pstep = %3.2e, dstep = %3.2e',pstep,dstep);
end
runhist.cputime(iter+1) = etime(clock,tstart);
termcode = -2;
breakyes = 1;
end
if (iter >= 2)
idx = max(2,iter-2) : iter;
pred_slow = all(mupredhist(idx)./mupredhist(idx-1) > 0.4);
idx = max(2,iter-5) : iter;
pred_convg_rate = mean(mupredhist(idx)./mupredhist(idx-1));
pred_slow = pred_slow + (mupred/mu > 5*pred_convg_rate);
end
if (~predcorr)
if (max(mu,infeas) < 1e-6) && (pred_slow) && (stoplevel)
msg = 'stop: lack of progress in predictor';
if (printlevel)
fprintf('\n %s',msg);
fprintf(': mupred/mu = %3.2f, pred_convg_rate = %3.2f.',...
mupred/mu,pred_convg_rate);
end
runhist.cputime(iter+1) = etime(clock,tstart);
termcode = -2;
breakyes = 1;
else
update_iter = 1;
end
end
%%
%%---------------------------------------------------------------
%% corrector step.
%%---------------------------------------------------------------
%%
if (predcorr) && (~breakyes)
step_pred = min(pstep,dstep);
if (mu > 1e-6)
if (step_pred < 1/sqrt(3));
expon_used = 1;
else
expon_used = max(expon,3*step_pred^2);
end
else
expon_used = max(1,min(expon,3*step_pred^2));
end
sigma = min( 1, (mupred/mu)^expon_used );
sigmu = sigma*mu;
%%
if (vers == 1)
[par,dX,dy,dZ] = HSDHKMcorr(blk,At,par,rp,Rd,sigmu,hRd,...
dX,dZ,coeff,L,X,Z);
elseif (vers == 2)
[par,dX,dy,dZ] = HSDNTcorr(blk,At,par,rp,Rd,sigmu,hRd,...
dX,dZ,coeff,L,X,Z);
end
if (solve_ok <= 0)
msg = 'stop: difficulty in computing corrector directions';
if (printlevel); fprintf('\n %s',msg); end
runhist.cputime(iter+1) = etime(clock,tstart);
termcode = -4;
break;
end
timenew = clock;
ttime.corr = ttime.corr + etime(timenew,timeold); timeold=timenew;
%%
%%-----------------------------------
%% step-lengths for corrector step
%%-----------------------------------
%%
if (gam == 0)
gamused = 0.9 + 0.09*min(pstep,dstep);
else
gamused = gam;
end
kapstep = max( (par.dkap<0)*(-kap/(par.dkap-eps)), (par.dkap>=0)*1e6 );
taustep = max( (par.dtau<0)*(-tau/(par.dtau-eps)), (par.dtau>=0)*1e6 );
Xstep = steplength(blk,X,dX,Xchol,invXchol);
timenew = clock;
ttime.corr_pstep = ttime.corr_pstep + etime(timenew,timeold); timeold=timenew;
Zstep = steplength(blk,Z,dZ,Zchol,invZchol);
timenew = clock;
pstep = min(1,gamused*min([Xstep,Zstep,kapstep,taustep]));
dstep = pstep;
kapcorr = kap + pstep*par.dkap;
taucorr = tau + pstep*par.dtau;
trXZcorr = trXZ + pstep*blktrace(blk,dX,Z) + dstep*blktrace(blk,X,dZ)...
+ pstep*dstep*blktrace(blk,dX,dZ);
mucorr = (trXZcorr+kapcorr*taucorr)/(nn+1);
ttime.corr_dstep = ttime.corr_dstep + etime(timenew,timeold); timeold=timenew;
%%
%%-----------------------------------------
%% stopping criteria for corrector step
%%-----------------------------------------
%%
if (iter >= 2)
idx = max(2,iter-2) : iter;
corr_slow = all(runhist.gap(idx)./runhist.gap(idx-1) > 0.8);
idx = max(2,iter-5) : iter;
corr_convg_rate = mean(runhist.gap(idx)./runhist.gap(idx-1));
corr_slow = corr_slow + (mucorr/mu > max(min(1,5*corr_convg_rate),0.8));
end
if (max(mu,infeas) < 1e-6) && (iter > 10) && (stoplevel) ...
&& (corr_slow && mucorr/mu > 1.0)
msg = 'stop: lack of progress in corrector';
if (printlevel)
fprintf('\n %s',msg);
fprintf(': mucorr/mu = %3.2f, corr_convg_rate = %3.2f',...
mucorr/mu,corr_convg_rate);
end
runhist.cputime(iter+1) = etime(clock,tstart);
termcode = -2;
breakyes = 1;
else
update_iter = 1;
end
end
%%
%%---------------------------------------------------------------
%% udpate iterate
%%---------------------------------------------------------------
%%
indef = [1 1];
if (update_iter)
for t = 1:5
[Xchol,indef(1)] = blkcholfun(blk,ops(X,'+',dX,pstep));
timenew = clock;
ttime.pchol = ttime.pchol + etime(timenew,timeold); timeold = timenew;
if (indef(1)); pstep = 0.8*pstep; else break; end
end
if (t > 1); pstep = gamused*pstep; end
for t = 1:5
[Zchol,indef(2)] = blkcholfun(blk,ops(Z,'+',dZ,dstep));
timenew = clock;
ttime.dchol = ttime.dchol + etime(timenew,timeold); timeold = timenew;
if (indef(2)); dstep = 0.8*dstep; else break; end
end
if (t > 1); dstep = gamused*dstep; end
AdX = AXfun(blk,At,par.permA,dX);
AXtmp = AX(1:m) + pstep*AdX(1:m); tautmp = par.tau+pstep*par.dtau;
prim_infeasnew = norm(b-AXtmp/tautmp)/normb;
pinfeas_bad(1) = (prim_infeasnew > max([1e-8,relgap,10*infeas]));
pinfeas_bad(2) = (prim_infeasnew > max([1e-4,20*prim_infeas]) ...
&& (infeas < 1e-2));
pinfeas_bad(3) = (max([relgap,dual_infeas]) < 1e-4) ...
&& (prim_infeasnew > max([2*prim_infeas,10*dual_infeas,1e-7]));
if any(indef)
msg = 'stop: X, Z not both positive definite';
if (printlevel); fprintf('\n %s',msg); end
termcode = -3;
breakyes = 1;
elseif any(pinfeas_bad)
if (stoplevel) && (max(pstep,dstep)<=1) && (kap < 1e-3) ...
&& (prim_infeasnew > dual_infeas);
msg = 'stop: primal infeas has deteriorated too much';
if (printlevel); fprintf('\n %s, %2.1e',msg,prim_infeasnew);
fprintf(' %2.1d,%2.1d,%2.1d',...
pinfeas_bad(1),pinfeas_bad(2),pinfeas_bad(3));
end
termcode = -7;
breakyes = 1;
end
end
if (~breakyes)
X = ops(X,'+',dX,pstep);
y = y + dstep*dy; Z = ops(Z,'+',dZ,dstep);
theta = max(0, theta + pstep*par.dtheta);
kap = kap + pstep*par.dkap;
if (tau + pstep*par.dtau > theta); tau = tau + pstep*par.dtau; end
end
end
%%
%%--------------------------------------------------
%% perturb Z: do this step before checking for break
%%--------------------------------------------------
perturb_Z = 1;
if (~breakyes) && (perturb_Z)
trXZtmp = blktrace(blk,X,Z);
trXE = blktrace(blk,X,EE);
Zpert = max(1e-12,0.2*min(relgap,prim_infeas)).*normC./normE;
Zpert = min(Zpert,0.1*trXZtmp./trXE);
Zpert = min([1,Zpert,1.5*Zpertold]);
if (infeas < 1e-2)
Z = ops(Z,'+',EE,Zpert);
[Zchol,indef(2)] = blkcholfun(blk,Z);
if any(indef(2))
msg = 'stop: Z not positive definite';
if (printlevel); fprintf('\n %s',msg); end
termcode = -3;
breakyes = 1;
end
end
Zpertold = Zpert;
end
%%
%%---------------------------------------------------------------
%% compute rp, Rd, infeasibities, etc.
%%---------------------------------------------------------------
%%
y2 = [y; tau; theta];
AX = AXfun(blk,At,par.permA,X);
rp = [zeros(m,1); kap; -abar] - AX - Bmat*y2;
% Rd = ops(Atyfun(blk,At,par.permA,par.isspAy,-y2),'-',Z);
trXZ = blktrace(blk,X,Z);
mu = (trXZ+kap*tau)/(nn+1);
obj = [blktrace(blk,C,X), b'*y]/tau;
gap = trXZ/tau^2;
relgap = gap/(1+mean(abs(obj)));
ZpATy = ops(Z,'+',Atyfun(blk,At,par.permA,par.isspAy,[y;0;0]));
ZpATynorm = ops(ZpATy,'norm');
prim_infeas = norm(b-AX(1:m)/tau)/normb;
dual_infeas = ops(ops(C,'-',ops(ZpATy,'/',tau)),'norm')/normC;
infeas = max(prim_infeas,dual_infeas);
runhist.pobj(iter+1) = obj(1);
runhist.dobj(iter+1) = obj(2);
runhist.gap(iter+1) = gap;
runhist.relgap(iter+1) = relgap;
runhist.pinfeas(iter+1) = prim_infeas;
runhist.dinfeas(iter+1) = dual_infeas;
runhist.infeas(iter+1) = infeas;
runhist.cputime(iter+1) = etime(clock,tstart);
runhist.step(iter+1) = min(pstep,dstep);
runhist.kappa(iter+1) = kap;
runhist.tau(iter+1) = tau;
runhist.theta(iter+1) = theta;
runhist.useLU(iter+1) = use_LU;
timenew = clock;
ttime.misc = ttime.misc + etime(timenew,timeold); % timeold = timenew;
[hh,mm,ss] = mytime(sum(runhist.cputime));
if (printlevel>=3)
fprintf('\n%2.0f|%4.3f|%4.3f|',iter,pstep,dstep);
fprintf('%2.1e|%2.1e|%2.1e|',prim_infeas,dual_infeas,gap);
fprintf('%- 7.6e| %s:%s:%s|',mean(obj),hh,mm,ss);
fprintf('%2.1e|%2.1e|%2.1e|',kap,tau,theta);
end
%%
%%--------------------------------------------------
%% check convergence.
%%--------------------------------------------------
param.termcode = termcode;
param.kap = kap;
param.tau = tau;
param.theta = theta;
param.iter = iter;
param.obj = obj;
param.gap = gap;
param.relgap = relgap;
param.mu = mu;
param.prim_infeas = prim_infeas;
param.dual_infeas = dual_infeas;
param.AX = AX(1:m)/tau;
param.ZpATynorm = ZpATynorm/tau;
param.normX = ops(X,'norm')/tau;
param.normZ = ops(Z,'norm')/tau;
if (~breakyes)
[param,breakyes,use_olditer,msg] = HSDsqlpcheckconvg(param,runhist);
termcode = param.termcode; %% important
if (use_olditer)
X = ops(X,'-',dX,pstep);
y = y - dstep*dy;
Z = ops(Z,'-',dZ,dstep);
kap = kap - pstep*par.dkap;
tau = tau - pstep*par.dtau;
theta = theta - pstep*par.dtheta;
prim_infeas = runhist.pinfeas(iter);
dual_infeas = runhist.dinfeas(iter);
gap = runhist.gap(iter); relgap = runhist.relgap(iter);
obj = [runhist.pobj(iter), runhist.dobj(iter)];
end
end
%%--------------------------------------------------
%% check for break
%%--------------------------------------------------
newtol = max(relgap,infeas);
update_best(iter+1) = ~( newtol >= besttol ); %#ok
if update_best(iter+1),
Xbest = X; ybest = y; Zbest = Z;
besttol = newtol;
end
if besttol < 1e-4 && ~any(update_best(max(1,iter-1):iter+1))
msg = 'lack of progess in infeas';
if (printlevel); fprintf('\n %s',msg); end
termcode = -9;
breakyes = 1;
end
if besttol < 1e-3 && newtol > 1.2*besttol && theta < 1e-10 && kap < 1e-6
msg = 'lack of progress in infeas';
if (printlevel); fprintf('\n %s',msg); end
termcode = -9;
breakyes = 1;
end
if (breakyes > 0.5); break; end
end
%%---------------------------------------------------------------
%% end of main loop
%%---------------------------------------------------------------
%%
use_bestiter = 1;
if (use_bestiter) && (param.termcode <= 0)
X = Xbest; y = ybest; Z = Zbest;
% kap = kapbest; tau = taubest; theta = thetabest;
trXZ = blktrace(blk,X,Z);
obj = [blktrace(blk,C,X), b'*y]/tau;
gap = trXZ/tau^2;
relgap = gap/(1+mean(abs(obj)));
AX = AXfun(blk,At,par.permA,X);
ZpATy = ops(Z,'+',Atyfun(blk,At,par.permA,par.isspAy,[y;0;0]));
ZpATynorm = ops(ZpATy,'norm');
prim_infeas = norm(b-AX(1:m)/tau)/normb;
dual_infeas = ops(ops(C,'-',ops(ZpATy,'/',tau)),'norm')/normC;
infeas = max(prim_infeas,dual_infeas);
runhist.pobj(iter+1) = obj(1);
runhist.dobj(iter+1) = obj(2);
runhist.gap(iter+1) = gap;
runhist.relgap(iter+1) = relgap;
runhist.pinfeas(iter+1) = prim_infeas;
runhist.dinfeas(iter+1) = dual_infeas;
runhist.infeas(iter+1) = infeas;
end
%%---------------------------------------------------------------
%% produce infeasibility certificates if appropriate
%%---------------------------------------------------------------
%%
X = ops(X,'/',tau); y = y/tau; Z = ops(Z,'/',tau);
if (iter >= 1)
param.termcode = termcode;
param.obj = obj;
param.relgap = relgap;
param.prim_infeas = prim_infeas;
param.dual_infeas = dual_infeas;
param.AX = AX(1:m)/tau;
param.ZpATynorm = ZpATynorm/tau;
[X,y,Z,resid,reldist,param,msg2] = ...
HSDsqlpmisc(blk,At,C,b,X,y,Z,par.permZ,param);
termcode = param.termcode;
end
%%
%%---------------------------------------------------------------
%% recover unrestricted blk from linear blk
%%---------------------------------------------------------------
%%
for p = 1:size(blk,1)
if (ublkidx(p) == 1)
n = blk{p,2}/2;
X{p} = X{p}(1:n)-X{p}(n+1:2*n);
Z{p} = Z{p}(1:n);
end
end
%%
%%---------------------------------------------------------------
%% print summary
%%---------------------------------------------------------------
%%
dimacs = [prim_infeas; 0; dual_infeas; 0];
dimacs = [dimacs; [-diff(obj); gap]/(1+sum(abs(obj)))];
info.dimacs = dimacs;
info.termcode = termcode;
info.iter = iter;
info.obj = obj;
info.gap = gap;
info.relgap = relgap;
info.pinfeas = prim_infeas;
info.dinfeas = dual_infeas;
info.cputime = sum(runhist.cputime);
info.time = ttime;
info.resid = resid;
info.reldist = reldist;
info.normX = ops(X,'norm');
info.normy = norm(y);
info.normZ = ops(Z,'norm');
info.normA = ops(At,'norm');
info.normb = norm(b);
info.normC = ops(C,'norm');
info.msg1 = msg;
info.msg2 = msg2;
%%
if isoctave,
warning(w1.state,w1.identifier);
else
warning(w2.state,w2.identifier);
warning(w1.state,w1.identifier);
end
sqlpsummary(info,ttime,[],printlevel);
%%*****************************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
HSDlinsysolve.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/HSDSolver/HSDlinsysolve.m
| 6,495 |
utf_8
|
0644ae75443d221edcf585f5a5736fe5
|
%%***************************************************************
%% linsysolve: solve linear system to get dy, and direction
%% corresponding to unrestricted variables.
%%
%% [xx,coeff,L,resnrm] = linsysolve(schur,UU,EE,Bmat,rhs);
%%
%% child functions: mybicgstable.m
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%***************************************************************
function [xx,coeff,L,resnrm] = HSDlinsysolve(par,schur,UU,EE,Bmat,rhs)
global solve_ok msg
global nnzmat nnzmatold matfct_options matfct_options_old use_LU
spdensity = par.spdensity;
printlevel = par.printlevel;
iter = par.iter;
m = length(schur);
if (iter==1); use_LU = 0; matfct_options_old = ''; end %#ok
if isempty(nnzmatold); nnzmatold = 0; end %#ok
%%
%% diagonal perturbation
%% old: pertdiag = 1e-15*max(1,diagschur);
%%
diagschur = abs(full(diag(schur)));
const = 1e-2/max(1,norm(par.dy2));
alpha = max(1e-14,min(1e-10,const*norm(par.rp))/(1+norm(diagschur.*par.dy2)));
pertdiag = alpha*max(1e-8,diagschur); %% Note: alpha is close to 1e-15.
mexschurfun(schur,pertdiag);
%%if (printlevel); fprintf(' %3.1e ',alpha); end
if (par.depconstr) || (min(diagschur) < min([1e-20*max(diagschur), 1e-4]))
lambda = 0.1*min(1e-14,const*norm(par.rp)/(1+norm(par.diagAAt.*par.dy2)));
mexschurfun(schur,lambda*par.diagAAt);
%%if (printlevel); fprintf('*'); end
end
if (max(diagschur)/min(diagschur) > 1e14) && (par.blkdim(2) == 0) ...
&& (iter > 10)
tol = 1e-6;
idx = find(diagschur < tol); len = length(idx);
pertdiagschur = zeros(m,1);
if (len > 0 && len < 5) && (norm(rhs(idx)) < tol)
pertdiagschur(idx) = 1*ones(length(idx),1);
mexschurfun(schur,pertdiagschur);
if (printlevel); fprintf('#'); end
end
end
%%
%%
%%
UU = [UU, Bmat];
if ~isempty(EE)
len = max(max(EE(:,1)),max(EE(:,2)));
else
len = 0;
end
tmp = [len+1,len+3,-1; len+2,len+4,1; len+3,len+1,1; len+4,len+2,-1;
len+2,len+2,par.addschur]; %% this is the -inverse
EE = [EE; tmp];
ncolU = size(UU,2);
%%
%% assemble coefficient matrix
%%
if isempty(EE)
coeff.mat22 = [];
else
coeff.mat22 = spconvert(EE);
end
coeff.mat12 = UU;
coeff.mat11 = schur; %% important to use perturbed schur matrix
%%
%% pad rhs with zero vector
%% decide which solution methods to use
%%
rhs = [rhs; zeros(m+ncolU-length(rhs),1)];
if (ncolU > 300); use_LU = 1; end
%%
%% Cholesky factorization
%%
L = []; resnrm = []; xx = inf*ones(m,1);
if (~use_LU)
nnzmat = mexnnz(coeff.mat11);
% nnzmatdiff = (nnzmat ~= nnzmatold);
solve_ok = 1; solvesys = 1;
if (nnzmat > spdensity*m^2) || (m < 500)
matfct_options = 'chol';
else
matfct_options = 'spchol';
end
if (printlevel > 2); fprintf(' %s',matfct_options); end
L.matdim = length(schur);
if strcmp(matfct_options,'chol')
if issparse(schur); schur = full(schur); end;
if (iter<=5); %%--- to fix strange anonmaly in Matlab
mexschurfun(schur,1e-20,2);
end
L.matfct_options = 'chol';
[L.R,indef] = chol(schur);
L.perm = 1:m;
elseif strcmp(matfct_options,'spchol')
if ~issparse(schur); schur = sparse(schur); end;
L.matfct_options = 'spchol';
[L.R,indef,L.perm] = chol(schur,'vector');
L.Rt = L.R';
end
if (indef)
solve_ok = -2; solvesys = 0;
msg = 'HSDlinsysolve: Schur complement matrix not positive definite';
if (printlevel); fprintf('\n %s',msg); end
end
if (solvesys)
if (ncolU)
tmp = coeff.mat12'*linsysolvefun(L,coeff.mat12)-coeff.mat22;
if issparse(tmp); tmp = full(tmp); end
[L.Ml,L.Mu,L.Mp] = lu(tmp);
tol = 1e-16;
condest = max(abs(diag(L.Mu)))/min(abs(diag(L.Mu)));
if any(abs(diag(L.Mu)) < tol) || (condest > 1e50*sqrt(norm(par.diagAAt))); %% old: 1e30
solvesys = 0; solve_ok = -4;
use_LU = 1;
msg = 'SMW too ill-conditioned, switch to LU factor';
if (printlevel); fprintf('\n %s, %2.1e.',msg,condest); end
end
end
if (solvesys)
[xx,resnrm,solve_ok] = HSDbicgstab(coeff,rhs,L,[],[],printlevel);
if (solve_ok<=0) && (printlevel)
fprintf('\n warning: HSDbicgstab fails: %3.1f.',solve_ok);
end
end
end
if (solve_ok < 0)
if (m < 6000 && strcmp(matfct_options,'chol')) || ...
(m < 1e5 && strcmp(matfct_options,'spchol'))
use_LU = 1;
if (printlevel); fprintf('\n switch to LU factor'); end
end
end
end
%%
%% LU factorization
%%
if (use_LU)
nnzmat = mexnnz(coeff.mat11)+mexnnz(coeff.mat12);
% nnzmatdiff = (nnzmat ~= nnzmatold);
solve_ok = 1; %#ok
if ~isempty(coeff.mat22)
raugmat = [coeff.mat11, coeff.mat12; coeff.mat12', coeff.mat22];
else
raugmat = coeff.mat11;
end
if (nnzmat > spdensity*m^2) || (m+ncolU < 500)
matfct_options = 'lu';
else
matfct_options = 'splu';
end
if (printlevel > 2); fprintf(' %s ',matfct_options); end
L.matdim = length(raugmat);
if strcmp(matfct_options,'lu')
if issparse(raugmat); raugmat = full(raugmat); end
L.matfct_options = 'lu';
[L.L,L.U,L.p] = lu(raugmat,'vector');
elseif strcmp(matfct_options,'splu')
if ~issparse(raugmat); raugmat = sparse(raugmat); end
L.matfct_options = 'splu';
[L.L,L.U,L.p,L.q,L.s] = lu(raugmat,'vector');
L.s = full(diag(L.s));
elseif strcmp(matfct_options,'ldl')
if issparse(raugmat); raugmat = full(raugmat); end
L.matfct_options = 'ldl';
[L.L,L.D,L.p] = ldl(raugmat,'vector');
L.D = sparse(L.D);
elseif strcmp(matfct_options,'spldl')
if ~issparse(raugmat); raugmat = sparse(raugmat); end
L.matfct_options = 'spldl';
[L.L,L.D,L.p,L.s] = ldl(raugmat,'vector');
L.s = full(diag(L.s));
L.Lt = L.L';
end
[xx,resnrm,solve_ok] = HSDbicgstab(coeff,rhs,L,[],[],printlevel);
if (solve_ok<=0) && (printlevel)
fprintf('\n warning: HSDbicgstab fails: %3.1f,',solve_ok);
end
end
if (printlevel>=3); fprintf('%2.0f ',length(resnrm)-1); end
%%
nnzmatold = nnzmat; matfct_options_old = matfct_options;
%%***************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
HSDsqlpmisc.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/HSDSolver/HSDsqlpmisc.m
| 3,299 |
utf_8
|
f36316ddff8099a74241fa1590fc584a
|
%%*****************************************************************************
%% HSDsqlpmisc:
%% produce infeasibility certificates if appropriate
%%
%% Input: X,y,Z are the original variables, not the HSD variables.
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004.
%%*****************************************************************************
function [X,y,Z,resid,reldist,param,msg] = HSDsqlpmisc(blk,At,C,b,X,y,Z,permZ,param)
obj = param.obj;
relgap = param.relgap;
prim_infeas = param.prim_infeas;
dual_infeas = param.dual_infeas;
ZpATynorm = param.ZpATynorm;
inftol = param.inftol;
m0 = param.m0;
indeprows = param.indeprows;
termcode = param.termcode;
AX = param.AX;
normX0 = param.normX0;
normZ0 = param.normZ0;
printlevel = param.printlevel;
%%
resid = []; reldist = []; msg = [];
Anorm = ops(At,'norm'); xnorm = ops(X,'norm'); ynorm = norm(y);
%%
if (termcode <= 0)
%%
%% To detect near-infeasibility when the algorithm provides
%% a "better" certificate of infeasibility than of optimality.
%%
err = max([prim_infeas,dual_infeas,relgap]);
% iflag = 0;
if (obj(2) > 0)
homRd = ZpATynorm/obj(2);
if (homRd < 1e-2*sqrt(err*inftol))
% iflag = 1;
termcode = 1;
param.termcode = 1;
end
elseif (obj(1) < 0)
homrp = norm(AX)/(-obj(1));
if (homrp < 1e-2*sqrt(err*inftol))
% iflag = 1;
termcode = 2;
param.termcode = 2;
end
end
end
if (termcode == 1)
rby = 1/(b'*y); y = rby*y; Z = ops(Z,'*',rby);
resid = ZpATynorm * rby;
reldist = ZpATynorm/(Anorm*ynorm);
msg = 'Stop: primal problem is suspected of being infeasible';
if (printlevel); fprintf('\n %s',msg); end
end
if (termcode == 2)
tCX = blktrace(blk,C,X);
X = ops(X,'*',1/(-tCX));
resid = norm(AX) /(-tCX);
reldist = norm(AX)/(Anorm*xnorm);
msg = 'Stop: dual problem is suspected of being infeasible';
if (printlevel); fprintf('\n %s',msg); end
end
if (termcode == 3)
maxblowup = max(ops(X,'norm')/normX0,ops(Z,'norm')/normZ0);
msg = sprintf('Stop: primal or dual is diverging, %3.1e',maxblowup);
if (printlevel); fprintf('\n %s',msg); end
end
[X,Z] = unperm(blk,permZ,X,Z);
if ~isempty(indeprows)
ytmp = zeros(m0,1);
ytmp(indeprows) = y;
y = ytmp;
end
%%*****************************************************************************
%% unperm: undo the permutations applied in validate.
%%
%% [X,Z,Xiter,Ziter] = unperm(blk,permZ,X,Z,Xiter,Ziter);
%%
%% undoes the permutation introduced in validate.
%% can also be called if Xiter and Ziter have not been set as
%%
%% [X,Z] = unperm(blk,permZ,X,Z);
%%
%% SDPT3: version 3.0
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last modified: 2 Feb 01
%%*****************************************************************************
function [X,Z] = unperm(blk,permZ,X,Z)
%%
for p = 1:size(blk,1)
if (strcmp(blk{p,1},'s') && ~isempty(permZ{p}))
per = permZ{p};
X{p} = X{p}(per,per);
Z{p} = Z{p}(per,per);
end
end
%%*****************************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
HSDbicgstab.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/HSDSolver/HSDbicgstab.m
| 3,084 |
utf_8
|
96ee9f939e0b2527113539aa0b633ffc
|
%%*************************************************************************
%% HSDbicgstab
%%
%% [xx,resnrm,flag] = HSDbicgstab(A,b,M1,tol,maxit)
%%
%% iterate on bb - (M1)*AA*x
%%
%% r = b-A*xtrue;
%%
%%*************************************************************************
function [xx,resnrm,flag] = HSDbicgstab(A,b,M1,tol,maxit,printlevel)
N = length(b);
if (nargin < 6); printlevel = 1; end
if (nargin < 5) || isempty(maxit); maxit = max(20,length(A.mat22)); end;
if (nargin < 4) || isempty(tol); tol = 1e-8; end;
tolb = min(1e-4,tol*norm(b));
flag = 1;
x = zeros(N,1);
if isstruct(A); r = b-matvec(A,x); else r = b-mexMatvec(A,x); end;
err = norm(r); resnrm(1) = err; minresnrm = err; xx = x;
%%if (err < tolb); return; end
omega = 1.0;
r_tld = r;
%%
%%
%%
smtol = 1e-40;
for iter = 1:maxit,
rho = (r_tld'*r);
if (abs(rho) < smtol)
flag = 2;
if (printlevel); fprintf('*'); end;
break;
end
if (iter > 1)
beta = (rho/rho_1)* (alp/omega);
p = r + beta*(p - omega*v);
else
p = r;
end
p_hat = precond(A,M1,p);
if isstruct(A); v = matvec(A,p_hat); else v = mexMatvec(A,p_hat); end;
alp = rho / (r_tld'*v);
s = r - alp*v;
%%
s_hat = precond(A,M1,s);
if isstruct(A); t = matvec(A,s_hat); else t = mexMatvec(A,s_hat); end;
omega = (t'*s) / (t'*t);
x = x + alp*p_hat + omega*s_hat;
r = s - omega*t;
rho_1 = rho;
%%
%% check convergence
%%
err = norm(r); resnrm(iter+1) = err; %#ok
if (err < minresnrm);
xx = x; minresnrm = err;
end
if (err < tolb)
break;
end
if (err > 10*minresnrm)
if (printlevel); fprintf('^'); end
break;
end
if (abs(omega) < smtol)
flag = 2;
if (printlevel); fprintf('*'); end;
break;
end
end
%%
%%*************************************************************************
%%*************************************************************************
%% matvec: matrix-vector multiply.
%% matrix = [A.mat11, A.mat12; A.mat12', A.mat22]
%%*************************************************************************
function Ax = matvec(A,x)
m = length(A.mat11); m2 = length(x)-m;
if (m2 > 0)
x1 = full(x(1:m));
else
x1 = full(x);
end
Ax = mexMatvec(A.mat11,x1);
if (m2 > 0)
x2 = full(x(m+1:m+m2));
Ax = Ax + mexMatvec(A.mat12,x2);
Ax2 = mexMatvec(A.mat12,x1,1) + mexMatvec(A.mat22,x2);
Ax = [Ax; Ax2];
end
%%*************************************************************************
%% precond:
%%*************************************************************************
function Mx = precond(A,L,x)
m = L.matdim; m2 = length(x)-m;
if (m2 > 0)
x1 = full(x(1:m));
else
x1 = full(x);
end
if (m2 > 0)
x2 = x(m+1:m+m2);
w = linsysolvefun(L,x1);
z = mexMatvec(A.mat12,w,1) -x2;
z = L.Mu \ (L.Ml \ (L.Mp*z));
x1 = x1 - mexMatvec(A.mat12,z);
end
%%
Mx = linsysolvefun(L,x1);
%%
if (m2 > 0)
Mx = [Mx; z];
end
%%*************************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
HSDHKMcorr.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/HSDSolver/HSDHKMcorr.m
| 985 |
utf_8
|
1e1983a66956f1d3e4e8e279b1dbe2d0
|
%%*****************************************************************
%% HSDHKMcorr: corrector step for the HKM direction.
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%*****************************************************************
function [par,dX,dy,dZ,resnrm] = HSDHKMcorr(blk,At,par,rp,Rd,sigmu,hRd,...
dX,dZ,coeff,L,X,Z)
global printlevel
global solve_ok
%%
[rhs,EinvRc] = HSDHKMrhsfun(blk,At,par,X,Z,rp,Rd,sigmu,hRd,dX,dZ);
m = length(rp); ncolU = size(coeff.mat12,2);
rhs = [rhs; zeros(m+ncolU-length(rhs),1)];
%%
solve_ok = 1; %#ok
[xx,resnrm,solve_ok] = HSDbicgstab(coeff,rhs,L,[],[],printlevel);
if (solve_ok<=0) && (printlevel)
fprintf('\n warning: iterative solver fails: %3.1f.',solve_ok);
end
if (par.printlevel>=3); fprintf('%2.0f ',length(resnrm)-1); end
%%
[par,dX,dy,dZ] = HSDHKMdirfun(blk,At,par,Rd,EinvRc,X,xx);
%%*****************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
HSDNTpred.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/HSDSolver/HSDNTpred.m
| 2,034 |
utf_8
|
e194daf53d375b24154b1caf94b7646d
|
%%**********************************************************************
%% HSDNTpred: Compute (dX,dy,dZ) for NT direction.
%%
%% compute SVD of Xchol*Zchol via eigenvalue decompostion of
%% Zchol * X * Zchol' = V * diag(sv2) * V'.
%% compute W satisfying W*Z*W = X.
%% W = G'*G, where G = diag(sqrt(sv)) * (invZchol*V)'
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%**********************************************************************
function [par,dX,dy,dZ,coeff,L,hRd] = ...
HSDNTpred(blk,At,par,rp,Rd,sigmu,X,Z,Zchol,invZchol)
global schurfun schurfun_par
%%
%% compute NT scaling matrix
%%
[par.W,par.G,par.sv,par.gamx,par.gamz,par.dd,par.ee,par.ff] = ...
NTscaling(blk,X,Z,Zchol,invZchol);
%%
%% compute schur matrix
%%
m = par.m;
schur = sparse(m+2,m+2);
UU = []; EE = [];
%%
for p = 1:size(blk,1)
pblk = blk(p,:);
if strcmp(pblk{1},'l')
[schur,UU,EE] = schurmat_lblk(blk,At,par,schur,UU,EE,p,par.dd);
elseif strcmp(pblk{1},'q');
[schur,UU,EE] = schurmat_qblk(blk,At,par,schur,UU,EE,p,par.dd,par.ee);
elseif strcmp(pblk{1},'s')
if isempty(schurfun{p})
schur = schurmat_sblk(blk,At,par,schur,p,par.W);
elseif ischar(schurfun{p})
if ~isempty(par.permZ{p})
Wp = par.W{p}(par.permZ{p},par.permZ{p});
else
Wp = par.W{p};
end
schurtmp = feval(schurfun{p},Wp,Wp,schurfun_par(p,:));
schur = schur + schurtmp;
end
end
end
%%
%% compute rhs
%%
[rhs,EinvRc,hRd] = HSDNTrhsfun(blk,At,par,X,Z,rp,Rd,sigmu);
%%
%% solve linear system
%%
par.addschur = par.kap/par.tau;
schur(m+1,m+1) = schur(m+1,m+1) + par.kap/par.tau;
schur(m+2,m+2) = schur(m+2,m+2) + par.addschur;
[xx,coeff,L] = HSDlinsysolve(par,schur,UU,EE,par.Umat,rhs);
%%
%% compute (dX,dZ)
%%
[par,dX,dy,dZ] = HSDNTdirfun(blk,At,par,Rd,EinvRc,xx);
%%**********************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
HSDsqlpCpert.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/HSDSolver/HSDsqlpCpert.m
| 2,263 |
utf_8
|
326ec0065ebb155fab5ee8b4670ec0db
|
%%*****************************************************************************
%% HSDsqlpCpert: perturb C.
%%
%%*****************************************************************************
function [At,Cpert] = HSDsqlpCpert(blk,At,par,C,X,Cpert,runhist)
iter = length(runhist.pinfeas);
prim_infeas = runhist.pinfeas(iter);
dual_infeas = runhist.dinfeas(iter);
relgap = runhist.relgap(iter);
infeas = runhist.infeas(iter);
theta = runhist.theta(iter);
%%
Cpertold = Cpert;
err = max(relgap,infeas);
for p = 1:size(blk,1)
pblk = blk(p,:);
n = sum(pblk{2});
tmp = max(1,norm(C{p},'fro'))/sqrt(n);
if (err < 1e-6)
if (norm(X{p},'fro') < 1e2); const=0.2; else const=0.3; end
Cpert(p) = max(const*Cpert(p),1e-10*tmp);
elseif (err < 1e-2)
if (norm(X{p},'fro') < 1e2); const=0.4; else const=0.5; end
Cpert(p) = max(const*Cpert(p),1e-8*tmp);
else
Cpert(p) = max(0.9*Cpert(p),1e-6*tmp);
end
Cpert = min(Cpert,Cpertold);
if (prim_infeas < min([0.1*dual_infeas, 1e-7*runhist.pinfeas(1)])) ...
&& (iter > 1 && dual_infeas > 0.8*runhist.dinfeas(iter-1) && relgap < 1e-4)
Cpert(p) = 0.5*Cpert(p);
elseif (dual_infeas < min([0.1*prim_infeas, 1e-7*runhist.dinfeas(1)])) ...
&& (iter > 1 && prim_infeas > 0.8*runhist.pinfeas(iter-1) && relgap < 1e-4)
Cpert(p) = 0.5*Cpert(p);
elseif (max(relgap,1e-2*infeas) < 1e-6 && relgap < 0.1*infeas)
Cpert(p) = 0.5*Cpert(p);
end
if (prim_infeas < min([1e-4*dual_infeas,1e-7]) && theta < 1e-6) ...
|| (prim_infeas < 1e-4 && theta < 1e-10)
Cpert(p) = 0.1*Cpert(p);
elseif (dual_infeas < min([1e-4*prim_infeas,1e-7]) && theta < 1e-6) ...
|| (dual_infeas < 1e-4 && theta < 1e-10)
Cpert(p) = 0.1*Cpert(p);
elseif (iter > 1 && theta > 0.9*runhist.theta(iter-1) && infeas < 1e-3)
Cpert(p) = 0.1*Cpert(p);
end
if strcmp(pblk{1},'s')
Cnew = C{p} + Cpert(p)*speye(n);
At{p}(:,par.invpermA(p,end-1)) = -svec(pblk,Cnew,1);
else
Cnew = C{p} + Cpert(p)*ones(n,1);
At{p}(:,par.invpermA(p,end-1)) = -Cnew;
end
end
%%*****************************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
cheby0.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Examples/cheby0.m
| 2,576 |
utf_8
|
a31e95ee5e80694cd1c3f2ceb594d369
|
%%**********************************************************
%% cheby0:
%%
%% minimize || p(d) ||_infty
%% p = polynomial of degree <= m such that p(0) = 1.
%%
%% Here d = n-vector
%%----------------------------------------------------------
%% [blk,Avec,C,b,X0,y0,Z0,objval,p] = cheby0(d,m,solve);
%%
%% d = a vector.
%% m = degree of polynomial.
%% feas = 1 if want feasible starting point
%% = 0 if otherwise.
%% solve = 0 if just want initialization
%% = 1 if want to solve the problem
%%
%% SDPT3: version 3.0
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last modified: 2 Feb 01
%%**********************************************************
function [blk,Avec,C,b,X0,y0,Z0,objval,p] = cheby0(d,m,solve);
if nargin <= 2; solve = 0; end;
if (size(d,1) < size(d,2)); d = d.'; end;
cmp = 1-isreal(d);
tstart=cputime;
n = length(d);
e = ones(n,1);
V(1:n,1) = e/norm(e); R(1,1) = 1/norm(e);
for i =1:m
v = d.*V(:,i);
for j = 1:i %% Arnoldi iterations:
H(j,i) = (V(:,j))'*v; %% constructing upper-Hessenberg matrix.
v = v - H(j,i)*V(:,j); %% orthonormaliztion of Krylov basis.
end;
H(i+1,i) = norm(v);
V(:,i+1) = v/H(i+1,i);
R(1:i+1,i+1) = (1/H(i+1,i))*([0; R(1:i,i)] - [R(1:i,1:i)*H(1:i,i); 0]);
end
if (cmp)
blk{1,1} = 'q'; blk{1,2} = 3*ones(1,n);
C = zeros(3*n,1); C(2:3:3*n) = ones(n,1);
b = [zeros(2*m,1); -1];
Atmp = [];
II = [0:3:3*n-3]'; ee = ones(n,1);
for k=1:m
dVk = d.*V(:,k);
Atmp = [Atmp; [2+II, k*ee, real(dVk)]; [3+II, k*ee, imag(dVk)]];
Atmp = [Atmp; [2+II, (m+k)*ee, -imag(dVk)]; [3+II, (m+k)*ee, real(dVk)]];
end
Atmp = [Atmp; [1+II, (2*m+1)*ee, -ones(n,1)]];
else
blk{1,1} = 'l'; blk{1,2} = 2*ones(1,n);
b = [zeros(m,1); -1];
C = [ones(n,1); -ones(n,1)];
Atmp = [];
II = [1:n]'; ee = ones(n,1);
for k=1:m
dVk = d.*V(:,k);
Atmp = [Atmp; [II, k*ee, dVk]; [n+II, k*ee, -dVk]];
end
Atmp = [Atmp; [II, (m+1)*ee, -ee]; [n+II, (m+1)*ee, -ee]];
end
Avec = spconvert(Atmp);
[X0,y0,Z0] = infeaspt(blk,Avec,C,b);
%%
if (solve)
[obj,X,y,Z] = sqlp(blk,Avec,C,b,[],X0,y0,Z0);
if (cmp)
y = y(1:m) + sqrt(-1)*y(m+1:2*m);
else
y = y(1:m);
end
x1 = R(1:m,1:m)*y(1:m);
p = [-x1(m:-1:1); 1];
objval = -mean(obj);
else
objval = []; p = [];
end
%%**********************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
randmat.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/randmat.m
| 782 |
utf_8
|
44e2c609bf458ffd5a37d9f816a0ea1b
|
%%******************************************************
%% randmat: generate an mxn matrix using matlab's
%% rand or randn functions using state = k.
%%
%%******************************************************
function v = randmat(m,n,k,randtype)
try
s = rng;
rng(k);
if strcmp(randtype,'n')
v = randn(m,n);
elseif strcmp(randtype,'u')
v = rand(m,n);
end
rng(s);
catch
if strcmp(randtype,'n')
s = randn('state'); %#ok
randn('state',k); %#ok
v = randn(m,n);
randn('state',s); %#ok
elseif strcmp(randtype,'u')
s = rand('state'); %#ok
rand('state',k); %#ok
v = rand(m,n);
rand('state',s); %#ok
end
end
%%******************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
skron.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/skron.m
| 1,389 |
utf_8
|
3aba6bed9dc50b45f766b4a8620c4ac3
|
%%***********************************************************************
%% skron: Find the matrix presentation of
%% symmetric kronecker product skron(A,B), where
%% A,B are symmetric.
%%
%% Important: A,B are assumed to be symmetric.
%%
%% K = skron(blk,A,B);
%%
%% blk: a cell array specifying the block diagonal structure of A,B.
%%
%% (ij)-column of K = 0.5*svec(AUB + BUA), where
%% U = xij*(ei*ej' + ej*ei')
%% xij = 1/2 if i=j
%% = 1/sqrt(2) otherwise.
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%***********************************************************************
function K = skron(blk,A,B)
if iscell(A) && ~ iscell(B)
error('skron: A,B must be both matrices or both cell arrays')
end
if iscell(A)
K = cell(size(blk,1),1);
for p = 1:size(blk,1)
if (norm(A{p}-B{p},'fro') < 1e-13)
sym = 1;
else
sym = 0;
end
if strcmp(blk{p,1},'s')
K{p} = mexskron(blk(p,:),A{p},B{p},sym);
end
end
else
if (norm(A-B,'fro') < 1e-13)
sym = 1;
else
sym = 0;
end
if strcmp(blk{1,1},'s')
K = mexskron(blk,A,B,sym);
end
end
%%***********************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
NTcorr.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/NTcorr.m
| 1,315 |
utf_8
|
458c52ec6bf00d3507df137889a53c7e
|
%%************************************************************************
%% NTcorr: corrector step for the NT direction.
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%************************************************************************
function [dX,dy,dZ] = NTcorr(blk,At,par,rp,Rd,sigmu,hRd,...
dX,dZ,coeff,L,X,Z)
global matfct_options solve_ok
printlevel = par.printlevel;
%%
[rhs,EinvRc] = NTrhsfun(blk,At,par,X,Z,rp,Rd,sigmu,hRd,dX,dZ);
m = length(rp); ncolU = size(coeff.mat12,2);
rhs = [rhs; zeros(m+ncolU-length(rhs),1)];
%%
if strcmp(matfct_options,'chol') || strcmp(matfct_options,'spchol') ...
|| strcmp(matfct_options,'ldl') || strcmp(matfct_options,'spldl')
[xx,resnrm,solve_ok] = symqmr(coeff,rhs,L,[],[],printlevel);
if (solve_ok<=0) && (printlevel)
fprintf('\n warning: symqmr fails: %3.1f.',solve_ok);
end
else
[xx,resnrm,solve_ok] = mybicgstab(coeff,rhs,L,[],[],printlevel);
if (solve_ok<=0) && (printlevel)
fprintf('\n warning: bicgstab fails: %3.1f.',solve_ok);
end
end
if (printlevel>=3); fprintf('%2.0d ',length(resnrm)-1); end
%%
[dX,dy,dZ] = NTdirfun(blk,At,par,Rd,EinvRc,xx,m);
%%************************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
HKMcorr.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/HKMcorr.m
| 1,313 |
utf_8
|
ff69a87fe927bf7f964fd55cbf7ec718
|
%%*****************************************************************
%% HKMcorr: corrector step for the HKM direction.
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%*****************************************************************
function [dX,dy,dZ,resnrm,EinvRc] = HKMcorr(blk,At,par,rp,Rd,sigmu,hRd,...
dX,dZ,coeff,L,X,Z)
global matfct_options solve_ok
printlevel = par.printlevel;
%%
[rhs,EinvRc] = HKMrhsfun(blk,At,par,X,Z,rp,Rd,sigmu,hRd,dX,dZ);
m = length(rp); ncolU = size(coeff.mat12,2);
rhs = [rhs; zeros(m+ncolU-length(rhs),1)];
%%
if strcmp(matfct_options,'chol') || strcmp(matfct_options,'spchol') ...
|| strcmp(matfct_options,'ldl') || strcmp(matfct_options,'spldl')
[xx,resnrm,solve_ok] = symqmr(coeff,rhs,L,[],[],printlevel);
if (solve_ok<=0) && (printlevel)
fprintf('\n warning: symqmr fails: %3.1f.',solve_ok);
end
else
[xx,resnrm,solve_ok] = mybicgstab(coeff,rhs,L,[],[],printlevel);
if (solve_ok<=0) && (printlevel)
fprintf('\n warning: bicgstab fails: %3.1f.',solve_ok);
end
end
if (printlevel>=3); fprintf('%2.0d ',length(resnrm)-1); end
%%
[dX,dy,dZ] = HKMdirfun(blk,At,par,Rd,EinvRc,X,xx,m);
%%*****************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
steplength.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/steplength.m
| 5,590 |
utf_8
|
2b52f7d5b9712cf17885f9ca3eaeb666
|
%%***************************************************************************
%% steplength: compute xstep such that X + xstep*dX >= 0.
%%
%% [xstep] = steplength(blk,X,dX,Xchol,invXchol);
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%***************************************************************************
function [xstep,invXchol] = steplength(blk,X,dX,Xchol,invXchol)
%%
for p = 1:size(blk,1)
pblk = blk(p,:);
numblk = length(pblk{2});
pblksize = sum(pblk{2});
if nnz(isnan(dX{p})) || nnz(isinf(dX{p}))
xstep = 0;
break;
end
if strcmp(pblk{1},'s')
if (max(pblk{2}) >= 200)
use_lanczos = 1;
else
use_lanczos = 0;
end
if (use_lanczos)
tol = 1e-3;
maxit = max(min(pblksize,30),round(sqrt(pblksize)));
[lam,delta] = lanczosfun(Xchol{p},-dX{p},maxit,tol);
%%
%% Note: lam <= actual largest eigenvalue <= lam + delta.
%%
d = lam+delta;
else
if isempty(invXchol{p});
invXchol{p} = inv(Xchol{p});
end
tmp = Prod2(pblk,dX{p},invXchol{p},0);
M = Prod2(pblk,invXchol{p}',tmp,1);
d = blkeig(pblk,-M);
end
tmp = max(d) + 1e-15*max(abs(d));
if (tmp > 0);
xstep(p) = 1/max(tmp); %#ok
else
xstep(p) = 1e12; %#ok
end
elseif strcmp(pblk{1},'q')
aa = qops(pblk,dX{p},dX{p},2);
bb = qops(pblk,dX{p},X{p},2);
cc = qops(pblk,X{p},X{p},2);
dd = bb.*bb - aa.*cc;
tmp = min(aa,bb);
idx = dd > 0 & tmp < 0;
steptmp = 1e12*ones(numblk,1);
if any(idx)
steptmp(idx) = -(bb(idx)+sqrt(dd(idx)))./aa(idx);
end
idx = abs(aa) < eps & bb < 0;
if any(idx)
steptmp(idx) = -cc(idx)./(2*bb(idx));
end
%%
%% also need first component to be non-negative
%%
ss = 1 + [0, cumsum(pblk{2})];
ss = ss(1:length(pblk{2}));
dX0 = dX{p}(ss);
X0 = X{p}(ss);
idx = dX0 < 0 & X0 > 0;
if any(idx)
steptmp(idx) = min(steptmp(idx),-X0(idx)./dX0(idx));
end
xstep(p) = min(steptmp); %#ok
elseif strcmp(pblk{1},'l')
idx = dX{p} < 0;
if any(idx)
xstep(p) = min(-X{p}(idx)./dX{p}(idx)); %#ok
else
xstep(p) = 1e12; %#ok
end
elseif strcmp(pblk{1},'u')
xstep(p) = 1e12; %#ok
end
end
xstep = min(xstep);
%%***************************************************************************
%%***************************************************************************
%% lanczos: find the largest eigenvalue of
%% invXchol'*dX*invXchol via the lanczos iteration.
%%
%% [lam,delta] = lanczosfun(Xchol,dX,maxit,tol,v)
%%
%% lam: an estimate of the largest eigenvalue.
%% lam2: an estimate of the second largest eigenvalue.
%% res: residual norm of the largest eigen-pair.
%% res2: residual norm of the second largest eigen-pair.
%%***************************************************************************
function [lam,delta,res] = lanczosfun(Xchol,dX,maxit,tol,v)
if (norm(dX,'fro') < 1e-13)
lam = 0; delta = 0; res = 0;
return;
end
n = length(dX);
if (nargin < 5);
v = randmat(n,1,0,'n');
end
if (nargin < 4); tol = 1e-3; end
if (nargin < 3); maxit = 30; end
V = zeros(n,maxit+1); H = zeros(maxit+1,maxit);
v = v/norm(v);
V(:,1) = v;
if issparse(Xchol); Xcholtransp = Xchol'; end
%%
%% lanczos iteration.
%%
for k = 1:maxit
if issparse(Xchol)
w = dX*mextriangsp(Xcholtransp,v,1);
w = mextriangsp(Xchol,w,2);
else
w = dX*mextriang(Xchol,v,1);
w = mextriang(Xchol,w,2);
end
wold = w;
if (k > 1);
w = w - H(k,k-1)*V(:,k-1);
end;
alp = w'*V(:,k);
w = w - alp*V(:,k);
H(k,k) = alp;
%%
%% one step of iterative refinement if necessary.
%%
if (norm(w) <= 0.8*norm(wold));
s = (w'*V(:,1:k))';
w = w - V(:,1:k)*s;
H(1:k,k) = H(1:k,k) + s;
end;
nrm = norm(w);
v = w/nrm;
V(:,k+1) = v;
H(k+1,k) = nrm; H(k,k+1) = nrm;
%%
%% compute ritz pairs and test for convergence
%%
if (rem(k,5) == 0) || (k == maxit);
Hk = H(1:k,1:k); Hk = 0.5*(Hk+Hk');
[Y,D] = eig(Hk);
eigH = real(diag(D));
[dummy,idx] = sort(eigH); %#ok
res_est = abs(H(k+1,k)*Y(k,idx(k)));
if (res_est <= 0.1*tol) || (k == maxit);
lam = eigH(idx(k));
lam2 = eigH(idx(k-1));
z = V(:,1:k)*Y(:,idx(k));
z2 = V(:,1:k)*Y(:,idx(k-1));
if issparse(Xchol)
tmp = dX*mextriangsp(Xcholtransp,z,1);
res = norm(mextriangsp(Xchol,tmp,2) -lam*z);
tmp = dX*mextriangsp(Xcholtransp,z2,1);
res2 = norm(mextriangsp(Xchol,tmp,2) -lam*z2);
else
tmp = dX*mextriang(Xchol,z,1);
res = norm(mextriang(Xchol,tmp,2) -lam*z);
tmp = dX*mextriang(Xchol,z2,1);
res2 = norm(mextriang(Xchol,tmp,2) -lam*z2);
end
tmp = lam-lam2 -res2;
if (tmp > 0); beta = tmp; else beta = eps; end;
delta = min(res,res^2/beta);
if (delta <= tol); break; end;
end
end
end
%%***************************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
SDPT3data_SEDUMIdata.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/SDPT3data_SEDUMIdata.m
| 3,843 |
utf_8
|
26106829dfa4c0fbb1ca8c4aa9839fa8
|
%%**********************************************************
%% SDPT3data_SEDUMIdata: convert SQLP data in SDPT3 format to
%% SeDuMi format
%%
%% [At,b,c,K] = SDPT3data_SEDUMIdata(blk,AAt,CC,bb);
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%**********************************************************
function [At,b,c,K] = SDPT3data_SEDUMIdata(blk,AAt,CC,bb)
c = []; At = [];
b = bb;
mm = length(bb);
%%
if (~iscell(CC))
Ctmp = CC; clear CC; CC{1} = Ctmp;
end
%%
%% extract unrestricted blk
%%
for p = 1:size(blk,1)
pblk = blk(p,:);
if (p==1); K.f = []; end
if strcmp(pblk{1},'u')
K.f = [K.f, pblk{2}];
At = [At; AAt{p}]; %#ok
c = [c; CC{p}]; %#ok
end
end
K.f = sum(K.f);
%%
%% extract linear blk
%%
for p = 1:size(blk,1)
pblk = blk(p,:);
if (p==1); K.l = []; end
if strcmp(pblk{1},'l')
K.l = [K.l, pblk{2}];
At = [At; AAt{p,1}]; %#ok
c = [c; CC{p,1}]; %#ok
end
end
K.l = sum(K.l);
%%
%% extract second order cone blk
%%
for p = 1:size(blk,1)
pblk = blk(p,:);
if (p==1); K.q = []; end
if strcmp(pblk{1},'q')
K.q = [K.q, pblk{2}];
At = [At; AAt{p,1}]; %#ok
c = [c; CC{p,1}]; %#ok
end
end
%%
%% extract rotated cone blk
%%
for p = 1:size(blk,1)
pblk = blk(p,:);
if (p==1); K.r = []; end
if strcmp(pblk{1},'r')
K.r = [K.r, pblk{2}];
At = [At; AAt{p,1}]; %#ok
c = [c; CC{p,1}]; %#ok
end
end
%%
%% extract semidefinite cone blk
%%
for p = 1:size(blk,1)
if (p==1); K.s = []; end
pblk = blk(p,:);
if strcmp(pblk{1},'s')
K.s = [K.s, pblk{2}];
ss = [0,cumsum(pblk{2})];
idxstart = [0,cumsum(pblk{2}.*pblk{2})];
numblk = length(pblk{2});
nnzA = nnz(AAt{p,1});
II = zeros(2*nnzA,1);
JJ = zeros(2*nnzA,1);
VV = zeros(2*nnzA,1);
m2 = size(AAt{p,1},2);
if (length(pblk) > 2)
rr = [0, cumsum(pblk{3})];
dd = AAt{p,3};
idxD = [0; find(diff(dd(:,1))); size(dd,1)];
end
count = 0;
for k = 1:mm
if (k<= m2);
Ak = smat(pblk,AAt{p,1}(:,k),1);
else
idx = rr(k)+1 : rr(k+1);
Vk = AAt{p,2}(:,idx);
len = pblk{3}(k);
if (size(dd,2) == 4)
idx2 = idxD(k)+1:idxD(k+1);
Dk = spconvert([dd(idx2,2:4); len,len,0]);
elseif (size(dd,2) == 1);
Dk = spdiags(dd(idx),0,len,len);
end
Ak = Vk*Dk*Vk';
end
for tt = 1:numblk
if (numblk > 1)
idx = ss(tt)+1: ss(tt+1);
Aksub = full(Ak(idx,idx));
else
Aksub = Ak;
end
tmp = Aksub(:);
nzidx = find(tmp);
len = length(nzidx);
II(count+1:count+len,1) = idxstart(tt)+nzidx;
JJ(count+1:count+len,1) = k*ones(length(nzidx),1);
VV(count+1:count+len,1) = tmp(nzidx);
count = count + len;
end
end
II = II(1:count);
JJ = JJ(1:count);
VV = VV(1:count);
At = [At; spconvert([II,JJ,VV; sum(pblk{2}.*pblk{2}), mm, 0])]; %#ok
Cp = CC{p};
ctmp = [];
for tt = 1:numblk
if (numblk > 1)
idx = ss(tt)+1: ss(tt+1);
Csub = full(Cp(idx,idx));
else
Csub = Cp;
end
ctmp = [ctmp; Csub(:)]; %#ok
end
c = [c; ctmp]; %#ok
end
end
%%**********************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
schurmat_sblk.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/schurmat_sblk.m
| 4,549 |
utf_8
|
f992891144a934ab4edffde2a692e435
|
%%*******************************************************************
%% schurmat_sblk: compute Schur complement matrix corresponding to
%% SDP blocks.
%%
%% symm = 0, HKM
%% = 1, NT
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%*******************************************************************
function schur = schurmat_sblk(blk,At,par,schur,p,X,Y)
global nnzschur nzlistschur
iter = par.iter;
smallblkdim = par.smallblkdim;
if isempty(smallblkdim); smallblkdim = 50; end
if (nargin == 7); symm = 0; else symm = 1; Y = X; end;
m = length(schur);
pblk = blk(p,:);
if (iter == 1)
nnzschur(size(blk,1),1) = m*m;
nzlistschur = cell(size(blk,1),1);
end
%%
if (max(pblk{2}) > smallblkdim) || (length(pblk{2}) <= 10)
%%
%% compute schur for matrices that are very sparse.
%%
m1 = size(At{p,1},2);
if issparse(schur); schur = full(schur); end;
J = min(m1, find(par.nzlistA{p,1} < inf,1,'last')-1);
if (J > 0)
if issparse(X{p}) && ~issparse(Y{p}); X{p} = full(X{p}); end
if ~issparse(X{p}) && issparse(Y{p}); Y{p} = full(Y{p}); end
if (iter <= 3)
[nnzschur(p),nzlisttmp] = mexschur(pblk,At{p,1},par.nzlistA{p,1},...
par.nzlistA{p,2},par.permA(p,:),Y{p},X{p},J,symm,schur);
if (nnzschur(p) == mexnnz(nzlisttmp))
nzlistschur{p} = nzlisttmp;
else
nzlistschur{p} = [];
end
else
if isempty(nzlistschur{p})
mexschur(pblk,At{p,1},par.nzlistA{p,1},...
par.nzlistA{p,2},par.permA(p,:),Y{p},X{p},J,symm,schur);
else
mexschur(pblk,At{p,1},par.nzlistA{p,1},...
par.nzlistA{p,2},par.permA(p,:),Y{p},X{p},J,symm,schur,nzlistschur{p});
end
end
end
%%
%% compute schur for matrices that are not so sparse or dense.
%%
if (m1 < m) %% for low rank constraints
ss = [0, cumsum(pblk{3})];
len = sum(pblk{3});
dd = At{p,3};
DD = spconvert([dd(:,2:4); len,len,0]);
XVD = X{p}*At{p,2}*DD;
YVD = Y{p}*At{p,2}*DD;
end
L = find(par.nzlistAsum{p,1} < inf,1,'last') -1;
if (J < L)
len = par.nzlistAsum{p,1}(J+1); list = par.nzlistAsum{p,2}(1:len,:);
end
if (m1 > 0)
for k = J+1:m
if (k<=m1)
isspAk = par.isspA(p,k);
Ak = mexsmat(blk,At,isspAk,p,k);
if (k <= L)
idx1 = par.nzlistAsum{p,1}(k)+1; idx2 = par.nzlistAsum{p,1}(k+1);
list = [list; par.nzlistAsum{p,2}(idx1:idx2,:)]; %#ok
list = sortrows(list,[2 1]);
tmp = Prod3(pblk,X{p},Ak,Y{p},symm,list);
else
tmp = Prod3(pblk,X{p},Ak,Y{p},symm);
end
else %%--- for low rank constraints
idx = ss(k-m1)+1 :ss(k-m1+1);
tmp = XVD(:,idx)* (Y{p}*At{p,2}(:,idx))';
end
if (~symm)
tmp = 0.5*(mexsvec(pblk,tmp) + mexsvec(pblk,tmp'));
else
tmp = mexsvec(pblk,tmp);
end
permk = par.permA(p,k);
idx = par.permA(p,1:min(k,m1));
tmp2 = schur(idx,permk) + mexinprod(blk,At,tmp,min(k,m1),p);
schur(idx,permk) = tmp2;
schur(permk,idx) = tmp2';
end
end
if (m1 < m) %% for low rank constraints
m2 = m - m1;
XVtmp = XVD'*At{p,2};
YVtmp = At{p,2}'*YVD;
for k = 1:m2
idx0 = ss(k)+1 : ss(k+1);
tmp = XVtmp(:,idx0) .* YVtmp(:,idx0);
tmp = tmp*ones(length(idx0),1);
tmp3 = schur(m1+1:m1+m2,m1+k) + mexqops(pblk{3},tmp,ones(length(tmp),1),1);
schur(m1+1:m1+m2,m1+k) = tmp3;
end
end
else
%%--- for SDP block where each sub-block is small dimensional
if issparse(X{p}) && ~issparse(Y{p}); Y{p} = sparse(Y{p}); end
if ~issparse(X{p}) && issparse(Y{p}); X{p} = sparse(X{p}); end
tmp = mexskron(pblk,X{p},Y{p});
schurtmp = At{p,1}'*tmp*At{p,1};
%% schurtmp = 0.5*(schurtmp + schurtmp');
if (norm(par.permA(p,:)-(1:m)) > 0)
Perm = spconvert([(1:m)', par.permA(p,:)', ones(m,1)]);
schur = schur + Perm'*schurtmp*Perm;
else
schur = schur + schurtmp;
end
end
%%*******************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
blktrace.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/blktrace.m
| 2,084 |
utf_8
|
6a5c3d9ff74073a8e864c246727eaa86
|
%%**********************************************************************
%% blktrace: compute <X1,Z1> + ... + <Xp,Zp>
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%**********************************************************************
function trXZ = blktrace(blk,X,Z,parbarrier)
if (nargin == 3)
trXZ = 0;
for p = 1:size(blk,1)
pblk = blk(p,:);
if strcmp(pblk{1},'s')
if (length(pblk{2}) == 1)
trXZ = trXZ + sum(sum(X{p}.*Z{p}));
else
xx = mexsvec(pblk,X{p},0);
zz = mexsvec(pblk,Z{p});
trXZ = trXZ + xx'*zz;
end
else
trXZ = trXZ + sum(X{p}.*Z{p});
end
end
elseif (nargin == 4)
trXZ = 0;
for p = 1:size(blk,1)
pblk = blk(p,:);
if (norm(parbarrier{p}) == 0)
if strcmp(pblk{1},'s')
if (length(pblk{2}) == 1)
trXZ = trXZ + sum(sum(X{p}.*Z{p}));
else
xx = mexsvec(pblk,X{p},0);
zz = mexsvec(pblk,Z{p});
trXZ = trXZ + xx'*zz;
end
else
trXZ = trXZ + sum(X{p}.*Z{p});
end
else
idx = find(parbarrier{p} == 0);
if ~isempty(idx)
if strcmp(pblk{1},'s')
sumXZ = sum(X{p}.*Z{p});
ss = [0,cumsum(pblk{2})];
for k = 1:length(idx)
idxtmp = ss(idx(k))+1:ss(idx(k)+1);
trXZ = trXZ + sum(sumXZ(idxtmp));
end
elseif strcmp(pblk{1},'q')
tmp = qops(pblk,X{p},Z{p},1);
trXZ = trXZ + sum(tmp(idx));
elseif strcmp(pblk{1},'l')
trXZ = trXZ + sum(X{p}(idx).*Z{p}(idx));
end
end
end
end
end
%%**********************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
sqlpu2lblk.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/sqlpu2lblk.m
| 3,099 |
utf_8
|
1a67e45c349d19614e890521aed11db5
|
%%***************************************************************************
%% sqlpu2lblk: decide whether to convert ublk to lblk
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 10 Jul 2007
%%***************************************************************************
function [blk,At,C,X,Z,ublk2lblk,ublkidx] = sqlpu2lblk(blk,At,C,X,Z,par,convertlen)
%%
ublk2lblk = zeros(size(blk,1),1);
ublkidx = cell(size(blk,1),2);
for p = 1:size(blk,1)
pblk = blk(p,:); n0 = sum(pblk{2});
if strcmp(pblk{1},'u') && (pblk{2} > 0)
ublk2lblk(p) = 1;
if (pblk{2} > convertlen); return; end
AAt = At{p}*At{p}';
mexschurfun(AAt,1e-15*max(1,diag(AAt)));
% indef = 0;
[L.R,indef,L.perm] = chol(AAt,'vector');
L.d = full(diag(L.R)).^2;
if (~indef) && (max(L.d)/min(L.d) < 1e6)
ublk2lblk(p) = 0;
msg = '*** no conversion for ublk';
if (par.printlevel); fprintf(' %s',msg); end
else
dd(L.perm,1) = abs(L.d); %#ok
idxN = find(dd < 1e-11*mean(L.d));
idxB = setdiff((1:n0)',idxN);
ddB = dd(idxB);
ddN = dd(idxN);
if ~isempty(ddN) && ~isempty(ddB) && (min(ddB)/max(ddN) < 10)
idxN = []; idxB = (1:n0)';
end
ublkidx{p,1} = n0; ublkidx{p,2} = idxN;
if ~isempty(idxN)
restol = 1e-8;
[W,resnorm] = findcoeff(At{p}',idxB,idxN);
resnorm(2) = norm(C{p}(idxN) - W'*C{p}(idxB));
if (max(resnorm) < restol)
% feasible = 1;
blk{p,2} = length(idxB);
Atmp = At{p}';
At{p} = Atmp(:,idxB)';
C{p} = C{p}(idxB);
X{p} = X{p}(idxB); Z{p} = Z{p}(idxB);
msg = 'removed dependent columns in constraint matrix for ublk';
if (par.printlevel); fprintf('\n %s\n',msg); end
end
end
end
end
end
%%***************************************************************************
%%***************************************************************************
%% findcoeff:
%%
%% [W,resnorm] = findcoeff(A,idXB,idXN);
%%
%% idXB = indices of independent columns of A.
%% idxN = indices of dependent columns of A.
%%
%% AB = A(:,idxB); AN = A(:,idxN) = AB*W
%%
%% SDPT3: version 3.0
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last modified: 2 Feb 01
%%***************************************************************************
function [W,resnorm] = findcoeff(A,idxB,idxN)
AB = A(:,idxB);
AN = A(:,idxN);
n = size(AB,2);
%%
%%-----------------------------------------
%% find W so that AN = AB*W
%%-----------------------------------------
%%
[L,U,P,Q] = lu(sparse(AB));
rhs = P*AN;
Lhat = L(1:n,:);
W = Q*( U \ (Lhat \ rhs(1:n,:)));
resnorm = norm(AN-AB*W,'fro')/max(1,norm(AN,'fro'));
%%***************************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
Prod3.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/Prod3.m
| 1,677 |
utf_8
|
2ee9f0d732e5ea1f326bfcf275b0da3c
|
%%************************************************************
%% Prod3: compute the entries of Q = A*B*C specified in
%% nzlistQ.
%%
%% Q = Prod3(blk,A,B,C,sym,nzlistQ)
%% Important: (a) A is assumed to be symmetric if nzlistQ
%% has 2 columns (since mexProd2nz computes A'*B).
%% (b) The 2nd column of nzlistQ must be sorted in
%% ascending order.
%%
%% (optional) sym = 1, if Q is symmetric.
%% = 0, otherwise.
%% (optional) nzlistQ = list of non-zero elements of Q to be
%% computed.
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%************************************************************
function Q = Prod3(blk,A,B,C,sym,nzlistQ)
if (nargin<5); sym = 0; end;
checkcell = [iscell(A) iscell(B) iscell(C)];
if (nargin==6)
checkcell(1,4) = iscell(nzlistQ);
else
nzlistQ = inf;
end
%%
if any(checkcell-1)
if (size(blk,1) > 1)
error('Prod3: blk and A,B,C are not compatible');
end
if strcmp(blk{1},'s')
[len,len2] = size(nzlistQ);
if (len == 0); nzlistQ = inf; len2 = 1; end;
if (len2 == 1) && (nzlistQ == inf)
tmp = Prod2(blk,A,B,0);
Q = Prod2(blk,tmp,C,sym);
else
tmp = Prod2(blk,B,C,0);
Q = mexProd2nz(blk,A,tmp,nzlistQ);
if sym; Q = 0.5*(Q+Q'); end;
end
elseif strcmp(blk{1},'q') || strcmp(blk{1},'l') || strcmp(blk{1},'u')
Q = A.*B.*C;
end
else
error('Prod3: A,B,C,nzlistQ must all be matrices');
end
%%************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
sqlptermcode.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/sqlptermcode.m
| 1,230 |
utf_8
|
40b494719c3c614b6196dd9846778c4c
|
%%*************************************************************************
%% sqlptermcode.m: explains the termination code in sqlp.m
%%
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%*************************************************************************
function sqlptermcode
fprintf('\n 3: norm(X) or norm(Z) diverging');
fprintf('\n 2: dual problem is suspected to be infeasible')
fprintf('\n 1: primal problem is suspected to be infeasible')
fprintf('\n 0: max(relative gap,infeasibility) < gaptol');
fprintf('\n -1: relative gap < infeasibility');
fprintf('\n -2: lack of progress in predictor or corrector');
fprintf('\n -3: X or Z not positive definite');
fprintf('\n -4: difficulty in computing predictor or corrector direction');
fprintf('\n -5: progress in relative gap or infeasibility is bad');
fprintf('\n -6: maximum number of iterations reached');
fprintf('\n -7: primal infeasibility has deteriorated too much');
fprintf('\n -8: progress in relative gap has deteriorated');
fprintf('\n -9: lack of progress in infeasibility');
fprintf('\n')
%%*************************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
AXfun.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/AXfun.m
| 1,869 |
utf_8
|
e816cba65d629a72167375f9a7697b2f
|
%%*************************************************************************
%% AXfun: compute AX(k) = <Ak,X>, k = 1:m
%%
%% AX = AXfun(blk,At,permA,X);
%%
%% Note: permA may be set to [] if no permutation is neccessary.
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%*************************************************************************
function AX = AXfun(blk,At,permA,X)
if isempty(permA); ismtpermA = 1; else ismtpermA = 0; end
for p = 1:size(blk,1);
pblk = blk(p,:);
if strcmp(pblk{1},'s')
m1 = size(At{p,1},2);
if (p==1)
if (length(pblk) > 2); m2 = length(pblk{3}); else m2 = 0; end
m = m1 + m2;
AX = zeros(m,1); tmp = zeros(m,1);
end
if (~isempty(At{p,1}))
if (ismtpermA)
tmp = (svec(pblk,X{p})'*At{p,1})';
%%tmp = mexinprod(blk,At,svec(pblk,X{p}),m1,p);
else
tmp(permA(p,1:m1),1) = (svec(pblk,X{p})'*At{p,1})';
%%tmp(permA(p,1:m1),1) = mexinprod(blk,At,svec(pblk,X{p}),m1,p);
end
end
if (length(pblk) > 2) %% for low rank constraints
m2 = length(pblk{3});
dd = At{p,3};
len = sum(pblk{3});
DD = spconvert([dd(:,2:4); len,len,0]);
XVD = X{p}*At{p,2}*DD;
if (length(X{p}) > 1)
tmp2 = sum(At{p,2}.*XVD)';
else
tmp2 = (At{p,2}.*XVD)';
end
tmp(m1+1:m1+m2) = mexqops(pblk{3},tmp2,ones(length(tmp2),1),1);
end
AX = AX + tmp;
else
if (p==1); m = size(At{p,1},2); AX = zeros(m,1); tmp = zeros(m,1); end
AX = AX + (X{p}'*At{p,1})';
end
end
%%*************************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
NTpred.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/NTpred.m
| 1,963 |
utf_8
|
3a2374e8ffa4806b637e50e551b9c17c
|
%%**********************************************************************
%% NTpred: Compute (dX,dy,dZ) for NT direction.
%%
%% compute SVD of Xchol*Zchol via eigenvalue decompostion of
%% Zchol * X * Zchol' = V * diag(sv2) * V'.
%% compute W satisfying W*Z*W = X.
%% W = G'*G, where G = diag(sqrt(sv)) * (invZchol*V)'
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%**********************************************************************
function [par,dX,dy,dZ,coeff,L,hRd] = ...
NTpred(blk,At,par,rp,Rd,sigmu,X,Z,Zchol,invZchol)
global schurfun schurfun_par
%%
%% compute NT scaling matrix
%%
[par.W,par.G,par.sv,par.gamx,par.gamz,par.dd,par.ee,par.ff] = ...
NTscaling(blk,X,Z,Zchol,invZchol);
%%
%% compute schur matrix
%%
m = length(rp);
schur = sparse(m,m);
UU = []; EE = []; Afree = [];
%%
for p = 1:size(blk,1)
pblk = blk(p,:);
if strcmp(pblk{1},'l')
[schur,UU,EE] = schurmat_lblk(blk,At,par,schur,UU,EE,p,par.dd);
elseif strcmp(pblk{1},'q');
[schur,UU,EE] = schurmat_qblk(blk,At,par,schur,UU,EE,p,par.dd,par.ee);
elseif strcmp(pblk{1},'s')
if isempty(schurfun{p})
schur = schurmat_sblk(blk,At,par,schur,p,par.W);
elseif ischar(schurfun{p})
if ~isempty(par.permZ{p})
Wp = par.W{p}(par.permZ{p},par.permZ{p});
else
Wp = par.W{p};
end
schurtmp = feval(schurfun{p},Wp,Wp,schurfun_par(p,:));
schur = schur + schurtmp;
end
elseif strcmp(pblk{1},'u')
Afree = [Afree, At{p}']; %#ok
end
end
%%
%% compute rhs
%%
[rhs,EinvRc,hRd] = NTrhsfun(blk,At,par,X,Z,rp,Rd,sigmu);
%%
%% solve linear system
%%
[xx,coeff,L] = linsysolve(par,schur,UU,Afree,EE,rhs);
%%
%% compute (dX,dZ)
%%
[dX,dy,dZ] = NTdirfun(blk,At,par,Rd,EinvRc,xx,m);
%%**********************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
sqlp.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/sqlp.m
| 11,506 |
utf_8
|
d4acdbc7a5a1c0fd270f5d3de302c545
|
%%*****************************************************************************
%% sqlp: solve an semidefinite-quadratic-linear program
%% by infeasible path-following method.
%%
%% [obj,X,y,Z,info,runhist] = sqlp(blk,At,C,b,OPTIONS,X0,y0,Z0);
%%
%% Input: blk: a cell array describing the block diagonal structure of SQL data.
%% At: a cell array with At{p} = [svec(Ap1) ... svec(Apm)]
%% b,C: data for the SQL instance.
%% (X0,y0,Z0): an initial iterate (if it is not given, the default is used).
%% OPTIONS: a structure that specifies parameters required in sqlp.m,
%% (if it is not given, the default in sqlparameters.m is used).
%%
%% Output: obj = [<C,X> <b,y>].
%% (X,y,Z): an approximately optimal solution or a primal or dual
%% infeasibility certificate.
%% info.termcode = termination-code
%% info.iter = number of iterations
%% info.obj = [primal-obj, dual-obj]
%% info.cputime = total-time
%% info.gap = gap
%% info.pinfeas = primal_infeas
%% info.dinfeas = dual_infeas
%% runhist.pobj = history of primal objective value.
%% runhist.dobj = history of dual objective value.
%% runhist.gap = history of <X,Z>.
%% runhist.pinfeas = history of primal infeasibility.
%% runhist.dinfeas = history of dual infeasibility.
%% runhist.cputime = history of cputime spent.
%%----------------------------------------------------------------------------
%% The OPTIONS structure specifies the required parameters:
%% vers gam predcorr expon gaptol inftol steptol
%% maxit printlevel scale_data ...
%% (all have default values set in sqlparameters.m).
%%*************************************************************************
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%*************************************************************************
function [obj,X,y,Z,info,runhist] = sqlp(blk,At,C,b,OPTIONS,X0,y0,Z0)
if (nargin < 5); OPTIONS = []; end
isemptyAtb = 0;
if isempty(At) && isempty(b);
%% Add redundant constraint: <-I,X> <= 0
b = 0;
At = ops(ops(blk,'identity'),'*',-1);
numblk = size(blk,1);
blk{numblk+1,1} = 'l'; blk{numblk+1,2} = 1;
At{numblk+1,1} = 1; C{numblk+1,1} = 0;
isemptyAtb = 1;
end
%%
%%-----------------------------------------
%% get parameters from the OPTIONS structure.
%%-----------------------------------------
%%
matlabversion = sscanf(version,'%f');
if strcmp(computer,'PCWIN64') || strcmp(computer,'GLNXA64')
par.computer = 64;
else
par.computer = 32;
end
par.matlabversion = matlabversion(1);
par.vers = 0;
par.predcorr = 1;
par.gam = 0;
par.expon = 1;
par.gaptol = 1e-8;
par.inftol = 1e-8;
par.steptol = 1e-6;
par.maxit = 100;
par.printlevel = 3;
par.stoplevel = 1;
par.scale_data = 0;
par.spdensity = 0.4;
par.rmdepconstr = 0;
par.smallblkdim = 50;
par.schurfun = cell(size(blk,1),1);
par.schurfun_par = cell(size(blk,1),1);
%%
parbarrier = cell(size(blk,1),1);
for p = 1:size(blk,1)
pblk = blk(p,:);
if strcmp(pblk{1},'s') || strcmp(pblk{1},'q')
parbarrier{p} = zeros(1,length(pblk{2}));
elseif strcmp(pblk{1},'l') || strcmp(pblk{1},'u' )
parbarrier{p} = zeros(1,sum(pblk{2}));
end
end
parbarrier_0 = parbarrier;
%%
if nargin > 4,
if isfield(OPTIONS,'vers'); par.vers = OPTIONS.vers; end
if isfield(OPTIONS,'predcorr'); par.predcorr = OPTIONS.predcorr; end
if isfield(OPTIONS,'gam'); par.gam = OPTIONS.gam; end
if isfield(OPTIONS,'expon'); par.expon = OPTIONS.expon; end
if isfield(OPTIONS,'gaptol'); par.gaptol = OPTIONS.gaptol; end
if isfield(OPTIONS,'inftol'); par.inftol = OPTIONS.inftol; end
if isfield(OPTIONS,'steptol'); par.steptol = OPTIONS.steptol; end
if isfield(OPTIONS,'maxit'); par.maxit = OPTIONS.maxit; end
if isfield(OPTIONS,'printlevel'); par.printlevel = OPTIONS.printlevel; end
if isfield(OPTIONS,'stoplevel'); par.stoplevel = OPTIONS.stoplevel; end
if isfield(OPTIONS,'scale_data'); par.scale_data = OPTIONS.scale_data; end
if isfield(OPTIONS,'spdensity'); par.spdensity = OPTIONS.spdensity; end
if isfield(OPTIONS,'rmdepconstr'); par.rmdepconstr = OPTIONS.rmdepconstr; end
if isfield(OPTIONS,'smallblkdim'); par.smallblkdim = OPTIONS.smallblkdim; end
if isfield(OPTIONS,'parbarrier');
parbarrier = OPTIONS.parbarrier;
if isempty(parbarrier); parbarrier = parbarrier_0; end
if ~iscell(parbarrier);
tmp = parbarrier; clear parbarrier; parbarrier{1} = tmp;
end
if (length(parbarrier) < size(blk,1))
len = length(parbarrier);
parbarrier(len+1:size(blk,1)) = parbarrier_0(len+1:size(blk,1));
end
end
if isfield(OPTIONS,'schurfun');
par.schurfun = OPTIONS.schurfun;
if ~isempty(par.schurfun); par.scale_data = 0; end
end
if isfield(OPTIONS,'schurfun_par'); par.schurfun_par = OPTIONS.schurfun_par; end
if isempty(par.schurfun); par.schurfun = cell(size(blk,1),1); end
if isempty(par.schurfun_par); par.schurfun_par = cell(size(blk,1),1); end
end
if (size(blk,2) > 2); par.smallblkdim = 0; end
%%
%%-----------------------------------------
%% convert matrices to cell arrays.
%%-----------------------------------------
%%
if ~iscell(At); At = {At}; end;
if ~iscell(C); C = {C}; end;
if all(size(At) == [size(blk,1), length(b)]);
convertyes = zeros(size(blk,1),1);
for p = 1:size(blk,1)
if strcmp(blk{p,1},'s') && all(size(At{p,1}) == sum(blk{p,2}))
convertyes(p) = 1;
end
end
if any(convertyes)
if (par.printlevel);
fprintf('\n sqlp: converting At into required format');
end
At = svec(blk,At,ones(size(blk,1),1));
end
end
%%
%%-----------------------------------------
%% validate SQLP data.
%%-----------------------------------------
%%
% tstart = cputime;
[blk,At,C,b,blkdim,numblk,parbarrier] = validate(blk,At,C,b,par,parbarrier);
[blk,At,C,b,iscmp] = convertcmpsdp(blk,At,C,b);
if (iscmp) && (par.printlevel>=2);
fprintf('\n SQLP has complex data');
end
if (nargin <= 5) || (isempty(X0) || isempty(y0) || isempty(Z0));
par.startpoint = 1;
[X0,y0,Z0] = infeaspt(blk,At,C,b);
else
par.startpoint = 2;
if ~iscell(X0); X0 = {X0}; end;
if ~iscell(Z0); Z0 = {Z0}; end;
y0 = real(y0);
if (length(y0) ~= length(b));
error('sqlp: length of b and y0 not compatible');
end
[X0,Z0] = validate_startpoint(blk,X0,Z0,par.spdensity,iscmp);
end
if (par.printlevel>=2)
fprintf('\n num. of constraints = %2.0d',length(b));
if blkdim(1);
fprintf('\n dim. of sdp var = %2.0d,',blkdim(1));
fprintf(' num. of sdp blk = %2.0d',numblk(1));
end
if blkdim(2);
fprintf('\n dim. of socp var = %2.0d,',blkdim(2));
fprintf(' num. of socp blk = %2.0d',numblk(2));
end
if blkdim(3); fprintf('\n dim. of linear var = %2.0d',blkdim(3)); end
if blkdim(4); fprintf('\n dim. of free var = %2.0d',blkdim(4)); end
end
%%
%%-----------------------------------------
%% detect unrestricted blocks in linear blocks
%%-----------------------------------------
%%
user_supplied_schurfun = 0;
for p = 1:size(blk,1)
if ~isempty(par.schurfun{p}); user_supplied_schurfun = 1; end
end
if (user_supplied_schurfun == 0)
[blk2,At2,C2,ublkinfo,parbarrier2,X02,Z02] = ...
detect_ublk(blk,At,C,parbarrier,X0,Z0,par.printlevel);
else
blk2 = blk; At2 = At; C2 = C;
parbarrier2 = parbarrier; X02 = X0; Z02 = Z0;
ublkinfo = cell(size(blk2,1),1);
end
ublksize = blkdim(4);
for p = 1:size(ublkinfo,1)
ublksize = ublksize + length(ublkinfo{p});
end
%%
%%-----------------------------------------
%% detect diagonal blocks in semidefinite blocks
%%-----------------------------------------
%%
if (user_supplied_schurfun==0)
[blk3,At3,C3,diagblkinfo,diagblkchange,parbarrier3,X03,Z03] = ...
detect_lblk(blk2,At2,C2,b,parbarrier2,X02,Z02,par.printlevel);
else
blk3 = blk2; At3 = At2; C3 = C2;
parbarrier3 = parbarrier2; X03 = X02; Z03 = Z02;
diagblkchange = 0;
diagblkinfo = cell(size(blk3,1),1);
end
%%
%%-----------------------------------------
%% main solver
%%-----------------------------------------
%%
% exist_analytic_term = 0;
% for p = 1:size(blk3,1);
% idx = find(parbarrier3{p} > 0);
% if ~isempty(idx); exist_analytic_term = 1; end
% end
%
if (par.vers == 0);
if blkdim(1); par.vers = 1; else par.vers = 2; end
end
par.blkdim = blkdim;
par.ublksize = ublksize;
[obj,X3,y,Z3,info,runhist] = ...
sqlpmain(blk3,At3,C3,b,par,parbarrier3,X03,y0,Z03);
%%
%%-----------------------------------------
%% recover semidefinite blocks from linear blocks
%%-----------------------------------------
%%
if any(diagblkchange)
X2 = cell(size(blk2,1),1); Z2 = cell(size(blk2,1),1);
count = 0;
for p = 1:size(blk2,1)
pblk = blk2(p,:);
n = sum(pblk{2});
blkno = diagblkinfo{p,1};
idxdiag = diagblkinfo{p,2};
idxnondiag = diagblkinfo{p,3};
if ~isempty(idxdiag)
len = length(idxdiag);
Xtmp = [idxdiag,idxdiag,X3{end}(count+1:count+len); n, n, 0];
Ztmp = [idxdiag,idxdiag,Z3{end}(count+1:count+len); n, n, 0];
if ~isempty(idxnondiag)
[ii,jj,vv] = find(X3{blkno});
Xtmp = [Xtmp; idxnondiag(ii),idxnondiag(jj),vv]; %#ok
[ii,jj,vv] = find(Z3{blkno});
Ztmp = [Ztmp; idxnondiag(ii),idxnondiag(jj),vv]; %#ok
end
X2{p} = spconvert(Xtmp);
Z2{p} = spconvert(Ztmp);
count = count + len;
else
X2(p) = X3(blkno); Z2(p) = Z3(blkno);
end
end
else
X2 = X3; Z2 = Z3;
end
%%
%%-----------------------------------------
%% recover linear block from unrestricted block
%%-----------------------------------------
%%
numblk = size(blk,1);
numblknew = numblk;
X = cell(numblk,1); Z = cell(numblk,1);
for p = 1:numblk
n = blk{p,2};
if isempty(ublkinfo{p,1})
X{p} = X2{p}; Z{p} = Z2{p};
else
Xtmp = zeros(n,1); Ztmp = zeros(n,1);
Xtmp(ublkinfo{p,1}) = max(0,X2{p});
Xtmp(ublkinfo{p,2}) = max(0,-X2{p});
Ztmp(ublkinfo{p,1}) = max(0,Z2{p});
Ztmp(ublkinfo{p,2}) = max(0,-Z2{p});
if ~isempty(ublkinfo{p,3})
numblknew = numblknew + 1;
Xtmp(ublkinfo{p,3}) = X2{numblknew};
Ztmp(ublkinfo{p,3}) = Z2{numblknew};
end
X{p} = Xtmp; Z{p} = Ztmp;
end
end
%%
%%-----------------------------------------
%% recover complex solution
%%-----------------------------------------
%%
if (iscmp)
for p = 1:numblk
pblk = blk(p,:);
n = sum(pblk{2})/2;
if strcmp(pblk{1},'s');
X{p} = X{p}(1:n,1:n) + sqrt(-1)*X{p}(n+1:2*n,1:n);
Z{p} = Z{p}(1:n,1:n) + sqrt(-1)*Z{p}(n+1:2*n,1:n);
X{p} = 0.5*(X{p}+X{p}');
Z{p} = 0.5*(Z{p}+Z{p}');
end
end
end
if (isemptyAtb)
X = X(1:end-1); Z = Z(1:end-1);
end
%%*****************************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
infeaspt.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/infeaspt.m
| 5,422 |
utf_8
|
ed7ce61d1094307a576ad8ddfd42bd30
|
%%********************************************************************
%% infeaspt: generate an initial point for sdp.m
%%
%% [X0,y0,Z0] = infeaspt(blk,At,C,b,options,scalefac);
%%
%% options = 1 if want X0,Z0 to be scaled identity matrices
%% = 2 if want X0,Z0 to be scalefac*(identity matrices).
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%********************************************************************
function [X0,y0,Z0] = infeaspt(blk,At,C,b,options,scalefac)
%%
if (nargin < 5); options = 1; end;
if (options == 1); scalefac = []; end;
if (options == 2) && (nargin < 6); scalefac = 1000; end;
if (scalefac <= 0); error('scalefac must a positive number'); end;
%%
if ~iscell(At); At = {At}; end;
if ~iscell(C); C = {C}; end;
m = length(b);
if all(size(At) == [size(blk,1) m]);
convertyes = zeros(size(blk,1),1);
for p = 1:size(blk,1)
if strcmp(blk{p,1},'s') && all(size(At{p,1}) == sum(blk{p,2}))
convertyes(p) = 1;
end
end
if any(convertyes)
At = svec(blk,At,ones(size(blk,1),1));
end
end;
%%
%%[blk,At,C,b] = validate(blk,At,C,b);
%%
X0 = cell(size(C)); Z0 = cell(size(C));
m = length(b);
for p = 1:size(blk,1);
pblk = blk(p,:);
blktmp = pblk{2};
n = length(C{p});
y0 = zeros(m,1);
b2 = 1 + abs(b');
if (options == 1);
if strcmp(pblk{1},'s');
normAni = [];
X0{p} = sparse(n,n); Z0{p} = sparse(n,n);
ss = [0, cumsum(blktmp)];
tt = [0, cumsum(blktmp.*(blktmp+1)/2)];
for i = 1:length(pblk{2})
if ~isempty(At{p,1})
pos = tt(i)+1 : tt(i+1);
Ai = At{p,1}(pos,:);
normAni = 1+sqrt(sum(Ai.*Ai));
end
if (length(At(p,:)) >= 2) %% for low rank constraints
dd = At{p,3};
qq = [0, cumsum(pblk{3})]; normtmp = ones(1,length(pblk{3}));
idxD = [0; find(diff(dd(:,1))); size(dd,1)];
for k = 1:length(pblk{3})
idx = qq(k)+1 : qq(k+1);
idx2 = idxD(k)+1: idxD(k+1);
Ak = At{p,2}(:,idx);
ii = dd(idx2,2)-qq(k); %% undo cumulative indexing
jj = dd(idx2,3)-qq(k);
len = pblk{3}(k);
Dk = spconvert([ii,jj,dd(idx2,4); len,len,0]);
tmp = Ak'*Ak*Dk;
normtmp(1,k) = 1+sqrt(sum(sum(tmp.*tmp')));
end
normAni = [normAni, normtmp]; %#ok
end
pos = ss(i)+1 : ss(i+1); ni = length(pos);
tmp = C{p}(pos,pos);
normCni = 1+sqrt(sum(sum(tmp.*tmp)));
const = 10; %%--- old: const = 1;
constX = max([const,sqrt(ni),ni*(b2./normAni)]);
constZ = max([const,sqrt(ni),normAni,normCni]);
X0{p}(pos,pos) = constX*spdiags(1+1e-10*randmat(ni,1,0,'u'),0,ni,ni);
Z0{p}(pos,pos) = constZ*spdiags(1+1e-10*randmat(ni,1,0,'u'),0,ni,ni);
end
elseif strcmp(pblk{1},'q');
s = 1+[0, cumsum(blktmp)];
len = length(blktmp);
normC = 1+norm(C{p});
normA = 1+sqrt(sum(At{p,1}.*At{p,1}));
idenqX = zeros(sum(blktmp),1);
idenqZ = zeros(sum(blktmp),1);
idenqX(s(1:len)) = max([1,b2./normA])*sqrt(blktmp') ;
idenqZ(s(1:len)) = max([sqrt(blktmp); max([normA,normC])*ones(1,len)])';
idenqX(s(1:len)) = idenqX(s(1:len)).*(1+1e-10*randmat(len,1,0,'u'));
idenqZ(s(1:len)) = idenqZ(s(1:len)).*(1+1e-10*randmat(len,1,0,'u'));
X0{p} = idenqX;
Z0{p} = idenqZ;
elseif strcmp(pblk{1},'l');
normC = 1+norm(C{p});
normA = 1+sqrt(sum(At{p,1}.*At{p,1}));
const = 10; %%--- old: const =1;
constX = max([const,sqrt(n),sqrt(n)*b2./normA]);
constZ = max([const,sqrt(n),normA,normC]);
X0{p} = constX*(1+1e-10*randmat(n,1,0,'u'));
Z0{p} = constZ*(1+1e-10*randmat(n,1,0,'u'));
elseif strcmp(pblk{1},'u');
X0{p} = sparse(n,1);
Z0{p} = sparse(n,1);
else
error(' blk: some fields not specified correctly');
end;
elseif (options == 2);
if strcmp(pblk{1},'s');
n = sum(blktmp);
X0{p} = scalefac*spdiags(1+1e-10*randmat(n,1,0,'u'),0,n,n);
Z0{p} = scalefac*spdiags(1+1e-10*randmat(n,1,0,'u'),0,n,n);
elseif strcmp(pblk{1},'q');
s = 1+[0, cumsum(blktmp)];
len = length(blktmp);
idenq = zeros(sum(blktmp),1);
idenq(s(1:len)) = 1+1e-10*randmat(len,1,0,'u');
X0{p} = scalefac*idenq;
Z0{p} = scalefac*idenq;
elseif strcmp(pblk{1},'l');
X0{p} = scalefac*(1+1e-10*randmat(n,1,0,'u'));
Z0{p} = scalefac*(1+1e-10*randmat(n,1,0,'u'));
elseif strcmp(pblk{1},'u');
X0{p} = sparse(n,1);
Z0{p} = sparse(n,1);
else
error(' blk: some fields not specified correctly');
end
end
end
%%********************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
Arrow.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/Arrow.m
| 933 |
utf_8
|
4a1803a8a960eba5462879d0ae4cbb78
|
%%********************************************************
%% Arrow:
%%
%% Fx = Arrow(pblk,f,x,options);
%%
%% if options == 0;
%% Fx = Arr(F)*x
%% if options == 1;
%% Fx = Arr(F)^{-1}*x
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%********************************************************
function Fx = Arrow(pblk,f,x,options)
if nargin == 3; options = 0; end;
s = 1 + [0, cumsum(pblk{2})];
idx1 = s(1:length(pblk{2}));
if options == 0
inprod = mexqops(pblk{2},f,x,1);
Fx = mexqops(pblk{2},f(idx1),x,3) + mexqops(pblk{2},x(idx1),f,3);
Fx(idx1) = inprod;
else
gamf2 = mexqops(pblk{2},f,f,2);
gamprod = mexqops(pblk{2},f,x,2);
alpha = gamprod./gamf2;
Fx = mexqops(pblk{2},1./f(idx1),x,3) - mexqops(pblk{2},alpha./f(idx1),f,3);
Fx(idx1) = alpha;
end
%%
%%********************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
mybicgstab.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/mybicgstab.m
| 3,536 |
utf_8
|
7ae20f5d14c6533fd9a50b23a1e5c8b3
|
%%*************************************************************************
%% mybicgstab
%%
%% [xx,resnrm,flag] = mybicgstab(A,b,M1,tol,maxit)
%%
%% iterate on bb - (M1)*AA*x
%%
%% r = b-A*xtrue;
%%
%%*************************************************************************
function [xx,resnrm,flag] = mybicgstab(A,b,M1,tol,maxit,printlevel)
N = length(b);
if (nargin < 6); printlevel = 1; end
if (nargin < 5) || isempty(maxit); maxit = max(30,length(A.mat22)); end;
if (nargin < 4) || isempty(tol); tol = 1e-10; end;
tolb = min(1e-4,tol*norm(b));
flag = 1;
x = zeros(N,1);
if (norm(x))
if isstruct(A); r = b-matvec(A,x); else r = b-mexMatvec(A,x); end;
else
r =b;
end
err = norm(r); resnrm(1) = err; minresnrm = err; xx = x;
%%if (err < 1e-3*tolb); return; end
omega = 1.0;
r_tld = r;
%%
%%
%%
breakyes = 0;
smtol = 1e-40;
for iter = 1:maxit,
rho = (r_tld'*r);
if (abs(rho) < smtol)
flag = 2;
if (printlevel); fprintf('*'); end;
breakyes = 1;
break;
end
if (iter > 1)
beta = (rho/rho_1)* (alp/omega);
p = r + beta*(p - omega*v);
else
p = r;
end
p_hat = precond(A,M1,p);
if isstruct(A); v = matvec(A,p_hat); else v = mexMatvec(A,p_hat); end;
alp = rho / (r_tld'*v);
s = r - alp*v;
%%
s_hat = precond(A,M1,s);
if isstruct(A); t = matvec(A,s_hat); else t = mexMatvec(A,s_hat); end;
omega = (t'*s) / (t'*t);
x = x + alp*p_hat + omega*s_hat;
r = s - omega*t;
rho_1 = rho;
%%
%% check convergence
%%
err = norm(r); resnrm(iter+1) = err; %#ok
if (err < minresnrm);
xx = x; minresnrm = err;
end
if (err < tolb)
break;
end
if (err > 10*minresnrm)
if (printlevel); fprintf('^'); end
breakyes = 2;
break;
end
if (abs(omega) < smtol)
flag = 2;
if (printlevel); fprintf('*'); end
breakyes = 1;
break;
end
end
if (~breakyes) && (printlevel >=3); fprintf(' '); end
%%
%%*************************************************************************
%%*************************************************************************
%% precond:
%%*************************************************************************
function Mx = precond(A,L,x)
m = L.matdim; m2 = length(x)-m;
Mx = zeros(length(x),1);
for iter = 1
if norm(Mx); r = x - matvec(A,Mx); else r = x; end
if (m2 > 0)
r1 = full(r(1:m));
else
r1 = full(r);
end
if (m2 > 0)
r2 = r(m+1:m+m2);
w = linsysolvefun(L,r1);
z = mexMatvec(A.mat12,w,1) - r2;
z = L.Mu \ (L.Ml \ (L.Mp*z));
r1 = r1 - mexMatvec(A.mat12,z);
end
d = linsysolvefun(L,r1);
if (m2 > 0)
d = [d; z]; %#ok
end
Mx = Mx + d;
end
%%*************************************************************************
%%*************************************************************************
%% matvec: matrix-vector multiply.
%% matrix = [A.mat11, A.mat12; A.mat12', A.mat22]
%%*************************************************************************
function Ax = matvec(A,x)
m = length(A.mat11); m2 = length(x)-m;
if issparse(x); x = full(x); end
if (m2 > 0)
x1 = x(1:m);
else
x1 = x;
end
Ax = mexMatvec(A.mat11,x1);
if (m2 > 0)
x2 = x(m+1:m+m2);
Ax = Ax + mexMatvec(A.mat12,x2);
Ax2 = mexMatvec(A.mat12,x1,1) + mexMatvec(A.mat22,x2);
Ax = [full(Ax); full(Ax2)];
end
%%*************************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
degeneracy.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/degeneracy.m
| 5,175 |
utf_8
|
52287ec83b17f60c33554d7a25764672
|
%%***************************************************************
%% degeneracy: determine if an SDP problem is non-degenerate.
%%
%% [ddx,ddz,B1,B2,sig1,sig12] = degeneracy(blk,At,X,y,Z);
%%
%% Assume that strict complementarity holds:
%% for primal non-degeneracy, we need rank([B1 B2]) = m
%% for dual non-degeneracy, we need B1 to have full column rank.
%%
%%***************************************************************
function [ddx,ddz,XB1,XB2,ZB1,sig1,sig12] = degeneracy(blk,At,X,y,Z)
if ~iscell(X); tmp = X; clear X; X{1} = tmp; end;
if ~iscell(Z); tmp = Z; clear Z; Z{1} = tmp; end;
m = length(y); XB1 = []; XB2 = []; ZB1 = [];
numblk = size(blk,1);
%%
%%
%%
for p = 1:size(blk,1)
n = length(X{p});
if strcmp(blk{p,1},'s')
% mu = sum(sum(X{p}.*Z{p}))/n;
[Qx,Dx] = eig(full(X{p})); [dx,idx] = sort(diag(Dx));
Qx = Qx(:,idx(n:-1:1)); dx = dx(n:-1:1); dx = dx + max(dx)*eps;
% Dx = diag(dx);
[Qz,Dz] = eig(full(Z{p})); [dz,idx] = sort(diag(Dz));
Qz = Qz(:,idx); dz = dz + max(dz)*eps;
% Dz = diag(dz);
sep_option = 1;
if (sep_option==1)
tolx(p) = mean(sqrt(dx.*dz)); %#ok
tolz(p) = tolx(p); %#ok
elseif (sep_option==2)
ddtmp = dx./dz;
idxtmp = find(ddtmp<1e12);
len = max(3,min(idxtmp));
ddratio = ddtmp(len:n-1)./ddtmp(len+1:n);
[dummy,idxmax] = max(ddratio); %#ok
idxmax2 = idxtmp(idxtmp==len+idxmax-1);
tmptolx = mean(dx(idxmax2:idxmax2+1));
tmptolz = mean(dz(idxmax2:idxmax2+1));
tolx(p) = exp(mean(log([tmptolx tmptolz]))); %#ok
tolz(p) = tolx(p); %#ok
end
idxr = find(dx > tolx(p)); rp = length(idxr);
idxs = find(dz > tolz(p)); sp = length(idxs);
r(p) = rp; s(p) = sp; %#ok
prim_rank(p) = n*(n+1)/2 - (n-rp)*(n-rp+1)/2; %#ok
dual_rank(p) = (n-sp)*(n-sp+1)/2; %#ok
strict_comp(p) = (r(p)+s(p) == n); %#ok
if (nargout > 2)
Q1 = Qx(:,idxr); Q2 = Qx(:,setdiff(1:n,idxr));
B11 = zeros(m,rp*(rp+1)/2);
B22 = zeros(m,rp*(n-rp));
for k = 1:m
Ak = smat(blk(p,:),At{p}(:,k));
tmp = Q1'*Ak*Q2;
B22(k,:) = tmp(:)';
tmp = Q1'*Ak*Q1;
B11(k,:) = svec(blk(p,:),tmp)';
end
XB1 = [XB1, B11]; %#ok
XB2 = [XB2, sqrt(2)*B22]; %#ok
Qz1 = Qz(:,setdiff(1:n,idxs));
ZB11 = zeros(m,(n-sp)*(n-sp+1)/2);
for k = 1:m
Ak = smat(blk(p,:),At{p}(:,k));
tmp = Qz1'*Ak*Qz1;
ZB11(k,:) = svec(blk(p,:),tmp)';
end
ZB1 = [ZB1, ZB11]; %#ok
end
elseif strcmp(blk{p,1},'q')
error('qblk is not allowed at the moment.');
elseif strcmp(blk{p,1},'l')
% mu = X{p}'*Z{p}/n;
dx = sort(X{p}); dx = dx(n:-1:1);
dz = sort(Z{p});
tolx(p) = mean(sqrt(dx.*dz)); %#ok
tolz(p) = tolx(p); %#ok
idxr = find(dx > tolx(p)); rp = length(idxr);
idxs = find(dz > tolz(p)); sp = length(idxs);
r(p) = rp; s(p) = sp; %#ok
prim_rank(p) = rp; %#ok
dual_rank(p) = n-sp; %#ok
strict_comp(p) = (r(p)+s(p) == n); %#ok
if (nargout > 2)
idx = X{p} > tolx(p);
XB1 = [XB1, full(At{p}(idx,:))']; %#ok
zidx = Z{p} < tolz(p);
ZB1 = [ZB1, full(At{p}(zidx,:))']; %#ok
end
end
ddx{p} = dx; ddz{p} = dz; %#ok
fprintf('\n blkno = %1.0d, tol = %3.1e,%3.1e, m = %2.0d',...
p,tolx(p),tolz(p),m);
fprintf('\n n= %2.0d, r= %2.0d, s= %2.0d',n,r(p),s(p));
fprintf('\n n2-(n-r)2 = %2.0d',prim_rank(p));
fprintf('\n (n-s)2 = %2.0d',dual_rank(p));
fprintf('\n complemen = %2.1e %2.1e\n',max(dx+dz),min(dx+dz));
subplot(121)
color = (1-p/numblk)*[0 0 1] + (p/numblk)*[1 0 0];
semilogy(dx,'+','color',color); hold on;
semilogy(dz,'o','color',color);
semilogy([1 n],tolx(p)*[1 1],'color',color);
semilogy([1 n],tolz(p)*[1 1],'--','color',color);
title('eig(X) and eig(Z)');
subplot(122)
semilogy(dx+dz,'*','color',color); hold on;
title('dx+dz')
end
%%
%%
%%
subplot(121); hold off; subplot(122); hold off;
prim_non_degen = (sum(prim_rank) >= m);
dual_non_degen = (sum(dual_rank) <= m);
fprintf('\n sum(n2-(n-r)2) = %2.0d (>=m)',sum(prim_rank));
fprintf('\n sum((n-s)2) = %2.0d (<=m)',sum(dual_rank));
fprintf('\n nec. cond. prim_non_degen = %1d',prim_non_degen);
fprintf('\n nec. cond. dual_non_degen = %1d',dual_non_degen);
fprintf('\n strict_comp = %1d\n',all(strict_comp));
sig1 = svd(ZB1);
sig12 = svd([XB1, XB2]');
fprintf('\n svd(ZB1): max, min = %2.1e %2.1e, cond = %2.1e\n',...
max(sig1),min(sig1),max(sig1)/min(sig1));
fprintf(' svd([XB1, XB2]^T): max, min = %2.1e %2.1e, cond = %2.1e\n',...
max(sig12),min(sig12),max(sig12)/min(sig12));
%%***************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
mytime.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/mytime.m
| 557 |
utf_8
|
2d076b8ed1091521bbe986194c6e2b84
|
%%*********************************************
%% mytime:
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%*********************************************
function [hh,mm,ss] = mytime(t)
t = round(t);
h = floor(t/3600);
m = floor(rem(t,3600)/60);
s = rem(rem(t,60),60);
hh = num2str(h);
if (h > 0) && (m < 10)
mm = ['0',num2str(m)];
else
mm = num2str(m);
end
if (s < 10)
ss = ['0',num2str(s)];
else
ss = num2str(s);
end
%%**********************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
validate.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/validate.m
| 7,427 |
utf_8
|
60774ce6b3bd16bde97e4078d89db39b
|
%%***********************************************************************
%% validate: validate data
%%
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%***********************************************************************
function [blk,At,C,b,dim,nnblk,parbarrier] = ...
validate(blk,At,C,b,par,parbarrier)
if (nargin >= 5)
spdensity = par.spdensity;
else
spdensity = 0.4;
end
%%
if ~iscell(blk);
error('validate: blk must be a cell array'); end;
if (size(blk,2) < 2)
error('validate: blk must be a cell array with at least 2 columns');
end
if ~iscell(At) || ~iscell(C);
error('validate: At, C must be cell arrays');
end
if (size(At,1) ~= size(blk,1))
if (size(At,2) == size(blk,1));
At = At';
else
error('validate: size of At is not compatible with blk');
end
end
if (size(C,1) ~= size(blk,1))
if (size(C,2) == size(blk,1))
C = C';
else
error('validate: size of C is not compatible with blk');
end
end
if (min(size(b)) > 1); error('validate: b must be a vector'); end
if (size(b,1) < size(b,2)); b = b'; end
m = length(b);
%%
%%-----------------------------------------
%% validate blk, At, C
%%-----------------------------------------
%%
for p = 1:size(blk,1)
if (size(blk{p,2},1) > size(blk{p,2},2))
blk{p,2} = blk{p,2}';
end
pblk = blk(p,:);
n = sum(pblk{2});
numblk = length(pblk{2});
if strcmp(pblk{1},'s');
m1 = size(At{p,1},2);
n2 = sum(pblk{2}.*pblk{2}); n22 = sum(pblk{2}.*(pblk{2}+1))/2;
ntotal(p) = n22; %#ok
if ~all(size(C{p}) == n)
error('validate: blk and C are not compatible');
end
if (norm(C{p}-C{p}',inf) > 1e-13*norm(C{p},inf));
error('validate: C is not symmetric');
end
if all(size(At{p,1})==[m1, n22]) && m1~=n22
At{p,1} = At{p,1}';
end
if (~isempty(At{p,1})) && (size(At{p,1},1) ~= n22)
error('validate: blk and At not compatible');
end
if (nnz(At{p,1}) < spdensity*n22*m1)
if ~issparse(At{p,1}); At{p,1} = sparse(At{p,1}); end
end
if (length(pblk) > 2) %% for low rank constraints
len = sum(pblk{3});
if (size(pblk{1,3},2) < size(pblk{1,3},1))
blk{p,3} = blk{p,3}';
end
if any(size(At{p,2})- [n,len])
error(' low rank structure specified in blk and At not compatible')
end
if (length(At(p,:)) > 2) && ~isempty(At{p,3})
if all(size(At{p,3},2)-[1,4])
error(' low rank structure in At{p,3} not specified correctly')
end
if (size(At{p,3},2) == 1)
if (size(At{p,3},1) < size(At{p,3},2)); At{p,3} = At{p,3}'; end
lenn = length(At{p,3});
constrnum = mexexpand(pblk{3},(1:length(pblk{3}))');
At{p,3} = [constrnum, (1:lenn)', (1:lenn)', At{p,3}];
elseif (size(At{p,3},2) == 4)
dd = At{p,3};
[dummy,idxsort] = sort(dd(:,1)); %#ok
dd = dd(idxsort,:);
lenn = size(dd,1);
idxD = [0; find(diff(dd(:,1))); lenn];
ii = zeros(lenn,1); jj = zeros(lenn,1);
ss = [0,cumsum(pblk{3})];
for k = 1:length(pblk{3})
idx = idxD(k)+1 : idxD(k+1);
ii(idx) = dd(idx,2)+ss(k); %% convert to cumulative indexing
jj(idx) = dd(idx,3)+ss(k);
end
At{p,3} = [dd(:,1),ii,jj,dd(:,4)];
end
else
constrnum = mexexpand(pblk{3},(1:length(pblk{3}))');
At{p,3} = [constrnum, (1:len)', (1:len)', ones(len,1)];
end
end
if (nnz(C{p}) < spdensity*n2) || (numblk > 1);
if ~issparse(C{p}); C{p} = sparse(C{p}); end;
else
if issparse(C{p}); C{p} = full(C{p}); end;
end
elseif strcmp(pblk{1},'q') || strcmp(pblk{1},'l') || strcmp(pblk{1},'u');
ntotal(p) = n; %#ok
if (min(size(C{p})) ~= 1 || max(size(C{p})) ~= n);
error('validate: blk and C are not compatible');
end;
if (size(C{p},1) < size(C{p},2)); C{p} = C{p}'; end
if all(size(At{p,1}) == [m, n]) && m~=n;
At{p,1} = At{p,1}';
end
if ~all(size(At{p,1}) == [n,m]);
error('validate: blk and At not compatible');
end
if ~issparse(At{p,1});
At{p,1} = sparse(At{p,1});
end
if (nnz(C{p}) < spdensity*n);
if ~issparse(C{p}); C{p} = sparse(C{p}); end;
else
if issparse(C{p}); C{p} = full(C{p}); end;
end;
else
error(' blk: some fields are not specified correctly');
end
end
if (sum(ntotal) < m)
error(' total dimension of C should be > length(b)');
end
%%
%%-----------------------------------------
%% problem dimension
%%-----------------------------------------
%%
dim = zeros(1,4);
nnblk = zeros(1,2);
nn = zeros(size(blk,1),1);
for p = 1:size(blk,1)
pblk = blk(p,:);
if strcmp(pblk{1},'s')
dim(1) = dim(1) + sum(pblk{2});
nnblk(1) = nnblk(1) + length(pblk{2});
nn(p) = sum(pblk{2});
elseif strcmp(pblk{1},'q')
dim(2) = dim(2) + sum(pblk{2});
nnblk(2) = nnblk(2) + length(pblk{2});
nn(p) = length(pblk{2});
elseif strcmp(pblk{1},'l')
dim(3) = dim(3) + sum(pblk{2});
nn(p) = sum(pblk{2});
elseif strcmp(pblk{1},'u')
dim(4) = dim(4) + sum(pblk{2});
nn(p) = sum(pblk{2});
end
end
%%
%%-----------------------------------------
%% validate parbarrier
%%-----------------------------------------
%%
if (nargin == 6)
if ~iscell(parbarrier);
if (length(parbarrier) == size(blk,1))
tmp = parbarrier;
clear parbarrier;
parbarrier = cell(size(blk,1),1);
for p = 1:size(blk,1)
parbarrier{p} = tmp(p);
end
end
end
if (size(parbarrier,2) > size(parbarrier,1))
parbarrier = parbarrier';
end
for p = 1:size(blk,1)
pblk = blk(p,:);
if (size(parbarrier{p},1) > size(parbarrier{p},2))
parbarrier{p} = parbarrier{p}';
end
len = length(parbarrier{p});
if strcmp(pblk{1},'s') || strcmp(pblk{1},'q')
if (len == 1)
parbarrier{p} = parbarrier{p}*ones(1,length(pblk{2}));
elseif (len == 0)
parbarrier{p} = zeros(1,length(pblk{2}));
elseif (len ~= length(pblk{2}))
error('blk and parbarrier not compatible');
end
elseif strcmp(pblk{1},'l')
if (len == 1)
parbarrier{p} = parbarrier{p}*ones(1,sum(pblk{2}));
elseif (len == 0)
parbarrier{p} = zeros(1,sum(pblk{2}));
elseif (len ~= sum(pblk{2}))
error('blk and parbarrier not compatible');
end
elseif strcmp(pblk{1},'u')
parbarrier{p}= zeros(1,sum(pblk{2}));
end
end
end
%%***********************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
svec.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/svec.m
| 2,027 |
utf_8
|
43bbe7c274d2d1bfb1014fc2000f47e3
|
%*********************************************************
%% svec: compute the vector svec(M),
%%
%% x = svec(blk,M,isspx);
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%**********************************************************
function x = svec(blk,M,isspx)
if iscell(M)
if (size(blk,1) ~= size(M,1))
error('svec: number of rows in blk and M not equal');
end
if (nargin == 2)
%%if (size(M,2) == 1)
%% isspx = zeros(size(blk,1),1);
%%else
%% isspx = ones(size(blk,1),1);
%%end
isspx = ones(size(blk,1),1);
else
if (length(isspx) < size(blk,1))
isspx = ones(size(blk,1),1);
end
end
x = cell(size(blk,1),1);
for p=1:size(blk,1)
pblk = blk(p,:);
n = sum(pblk{2}); m = size(M,2);
if strcmp(pblk{1},'s')
n2 = sum(pblk{2}.*(pblk{2}+1))/2;
if (isspx(p));
x{p} = sparse(n2,m);
else
x{p} = zeros(n2,m);
end
numblk = length(pblk{2});
if (pblk{2} > 0)
for k = 1:m
if (numblk > 1) && ~issparse(M{p,k});
x{p}(:,k) = mexsvec(pblk,sparse(M{p,k}),isspx(p));
else
x{p}(:,k) = mexsvec(pblk,M{p,k},isspx(p));
end
end
end
else
if (isspx(p))
x{p} = sparse(n,m);
else
x{p} = zeros(n,m);
end
for k = 1:m
x{p}(:,k) = M{p,k};
end
end
end
else
if strcmp(blk{1},'s')
numblk = length(blk{2});
if (numblk > 1) && ~issparse(M);
x = mexsvec(blk,sparse(M),1);
else
x = mexsvec(blk,sparse(M));
end
else
x = M;
end
end
%%**********************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
read_sedumi.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/read_sedumi.m
| 7,265 |
utf_8
|
2035885c053fc9de89cf19fa667603d2
|
%%*******************************************************************
%% Read in a problem in SeDuMi format.
%%
%% [blk,A,C,b,perm] = read_sedumi(fname,b,c,K)
%%
%% Input: fname.mat = name of the file containing SDP data in
%% SeDuMi format.
%%
%% Important note: Sedumi's notation for free variables "K.f"
%% is coded in SDPT3 as blk{p,1} = 'u', where
%% "u" is used for unrestricted variables.
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%******************************************************************
function [blk,Avec,C,b,perm] = read_sedumi(fname,b,c,K,smallblkdim)
if (nargin < 5)
smallblkdim = 50;
end
A = 0;
At = 0;
if ischar(fname)
%%
%% load the matlab file containing At, c, b, and K
%%
K.f = []; K.l = []; K.q = [];
compressed = 0;
if exist([fname,'.mat.gz'],'file');
compressed = 1;
unix(['gunzip ', fname,'.mat.gz']);
elseif exist([fname,'.gz'],'file');
compressed = 2;
unix(['gunzip ', fname,'.gz']);
elseif exist([fname,'.mat.Z'],'file');
compressed = 3;
unix(['uncompress ', fname,'.mat.Z'],'file');
elseif exist([fname,'.Z'],'file');
compressed = 4;
unix(['uncompress ', fname,'.Z']);
end
if exist([fname,'.mat'],'file') || exist(fname,'file')
eval(['load ', fname]);
else
fprintf('*** Problem not found, please specify the correct path or problem. \n');
blk = []; Avec = []; C = []; b = [];
return;
end
if (compressed == 1)
unix(['gzip ', fname,'.mat']);
elseif (compressed == 2)
unix(['gzip ', fname]);
elseif (compressed == 3)
unix(['compress ', fname,'.mat']);
elseif (compressed == 4)
unix(['compress ', fname]);
end
elseif (nargin < 4)
error('read_sedumi: need 4 input ');
else
A = fname;
end
%%
if exist('c','var')
if (size(c,1) == 1), c = c'; end;
end
if exist('C','var')
c = C; %#ok
if (size(c,1) == 1), c = c'; end;
end
if (size(b,1) == 1), b = b'; end;
if (norm(A,'fro') > 0) && (size(A,2) == length(b)); At = A; end
%%
if (norm(At,'fro')==0), At = A'; end;
nn = size(At,1); if (max(size(c)) == 1); c = c*ones(nn,1); end;
if ~isfield(K,'f'); K.f = 0; end
if ~isfield(K,'l'); K.l = 0; end
if ~isfield(K,'q'); K.q = 0; end
if ~isfield(K,'s'); K.s = 0; end
if (K.f == 0) || isempty(K.f); K.f = 0; end;
if (K.l == 0) || isempty(K.l); K.l = 0; end;
if (sum(K.q) == 0) || isempty(K.q); K.q = 0; end
if (sum(K.s) == 0) || isempty(K.s); K.s = 0; end
%%
%%
%%
% m = length(b);
rowidx = 0; idxblk = 0;
if ~(K.f == 0)
len = K.f;
idxblk = idxblk + 1;
blk{idxblk,1} = 'u'; blk{idxblk,2} = K.f;
Atmp = At(rowidx+1:rowidx+len,:);
Avec{idxblk,1} = Atmp;
C{idxblk,1} = c(rowidx+1:rowidx+len);
perm{idxblk} = [];
rowidx = rowidx + len;
end
if ~(K.l == 0)
len = K.l;
idxblk = idxblk + 1;
blk{idxblk,1} = 'l'; blk{idxblk,2} = K.l;
Atmp = At(rowidx+1:rowidx+len,:);
Avec{idxblk,1} = Atmp;
C{idxblk,1} = c(rowidx+1:rowidx+len);
perm{idxblk} = [];
rowidx = rowidx + len;
end
if ~(K.q == 0)
len = sum(K.q);
idxblk = idxblk + 1;
blk{idxblk,1} = 'q';
if size(K.q,1) <= size(K.q,2);
blk{idxblk,2} = K.q;
else
blk{idxblk,2} = K.q';
end
Atmp = At(rowidx+1:rowidx+len,:);
Avec{idxblk,1} = Atmp;
C{idxblk,1} = c(rowidx+1:rowidx+len);
perm{idxblk} = [];
rowidx = rowidx + len;
end
if ~(K.s == 0)
blksize = K.s;
if (size(blksize,2) == 1); blksize = blksize'; end
blknnz = [0, cumsum(blksize.*blksize)];
deblkidx = find(blksize > smallblkdim);
if ~isempty(deblkidx)
for p = 1:length(deblkidx)
idxblk = idxblk + 1;
n = blksize(deblkidx(p));
pblk{1,1} = 's'; pblk{1,2} = n;
blk(idxblk,:) = pblk;
Atmp = At(rowidx+blknnz(deblkidx(p))+(1:n*n),:);
%%
%% column-wise positions of upper triangular part
%%
tmp = triu(ones(n)); tmp = tmp(:);
idxtriu = find(tmp);
%%
%% row-wise positions of lower triangular part
%%
tmp = tril(reshape(1:n*n,n,n)); tmp = tmp(:);
idxtmp = find(tmp);
[dummy,idxsub] = sort(rem(tmp(idxtmp),n)); %#ok
idxtril = [idxtmp(idxsub(n+1:end));idxtmp(idxsub(1:n))];
%%
tmp2 = sqrt(2)*triu(ones(n),1) + speye(n,n);
tmp2 = tmp2(:);
dd = tmp2(tmp2~=0);
n2 = n*(n+1)/2;
Atmptriu = Atmp(idxtriu,:); %#ok
Atmptril = Atmp(idxtril,:);
if (norm(Atmptriu-Atmptril,'fro') > 1e-13)
fprintf('\n warning: constraint matrices not symmetric.');
fprintf('\n matrices are symmetrized.\n');
Atmptriu = 0.5*(Atmptriu+Atmptril);
end
Avec{idxblk,1} = spdiags(dd,0,n2,n2)*Atmptriu;
Ctmp = c(rowidx+blknnz(deblkidx(p))+(1:n*n));
Ctmp = mexmat(pblk,Ctmp,1);
C{idxblk,1} = 0.5*(Ctmp+Ctmp'); %#ok
perm{idxblk,1} = deblkidx(p);
end
end
spblkidx = find(blksize <= smallblkdim);
if ~isempty(spblkidx)
cnt = 0; cnt2 = 0;
spblksize = blksize(spblkidx);
nn = sum(spblksize.*spblksize);
nn2 = sum(spblksize.*(spblksize+1)/2);
pos = zeros(nn,1);
dd = zeros(nn2,1);
idxtriu = zeros(nn2,1);
idxtril = zeros(nn2,1);
for p = 1:length(spblkidx)
n = blksize(spblkidx(p));
n2 = n*(n+1)/2;
pos(cnt+1:cnt+n*n) = rowidx+blknnz(spblkidx(p))+(1:n*n);
%%
%% column-wise positions of upper triangular part
%%
tmp = triu(ones(n)); tmp = tmp(:);
idxtriu(cnt2+1:cnt2+n2) = cnt+find(tmp);
%%
%% row-wise positions of lower triangular part
%%
tmp = tril(reshape(1:n*n,n,n)); tmp = tmp(:);
idxtmp = find(tmp);
[dummy,idxsub] = sort(rem(tmp(idxtmp),n)); %#ok
idxtril(cnt2+1:cnt2+n2) = cnt+[idxtmp(idxsub(n+1:end));idxtmp(idxsub(1:n))];
%%
tmp2 = sqrt(2)*triu(ones(n),1) + speye(n,n);
tmp2 = tmp2(:);
dd(cnt2+1:cnt2+n2) = tmp2(tmp2~=0);
cnt = cnt + n*n;
cnt2 = cnt2 + n2;
end
idxblk = idxblk + 1;
blk{idxblk,1} = 's'; blk{idxblk,2} = blksize(spblkidx);
Atmp = At(pos,:);
Atmptriu = Atmp(idxtriu,:);
Atmptril = Atmp(idxtril,:);
if (norm(Atmptriu-Atmptril,'fro') > 1e-13)
fprintf('\n warning: constraint matrices not symmetric.');
fprintf('\n matrices are symmetrized.\n');
Atmptriu = 0.5*(Atmptriu+Atmptril);
end
Avec{idxblk,1} = spdiags(dd,0,length(dd),length(dd))*Atmptriu;
Ctmp = c(pos);
Ctmp = mexmat(blk(idxblk,:),Ctmp,1);
C{idxblk,1} = 0.5*(Ctmp+Ctmp');
perm{idxblk,1} = spblkidx;
end
end
%%
%%*******************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
qprod.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/qprod.m
| 655 |
utf_8
|
2d6550b139b2dfcf3d134f61deec3686
|
%%***************************************************
%% qprod:
%%
%% Input: A = [A1 A2 ... An]
%% x = [x1; x2; ...; xn]
%% Output: [A1*x1 A2*x2 ... An*xn]
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%***************************************************
function Ax = qprod(pblk,A,x)
if (size(pblk,1) > 1)
error('qprod: pblk can only have 1 row');
end
if issparse(x); x = full(x); end; %% for spconvert
n = length(x);
ii = (1:n)';
jj = mexexpand(pblk{2},(1:length(pblk{2}))');
X = spconvert([ii, jj, x]);
Ax = A*X;
%%***************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
nzlist.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/nzlist.m
| 5,014 |
utf_8
|
1225b63fe9e00df09546243f60599dc2
|
%%***********************************************************************
%% nzlist: find the combined list of non-zero elements
%% of Aj, j = 1:k, for each k,
%% assuming that the Aj's are permuted such that
%% A1 has the fewest nonzero elements, followed by A2, and so on.
%%
%% [isspA,nzlistA,nzlistAsum,isspAy,nzlistAy] = nzlist(blk,At,par)
%%
%% isspA(p,k) = 1 if Apk is sparse, 0 if it is dense.
%% nzlistA = px2 cell array.
%% nzlistA{p,1}(k) is the starting row index (in C convention)
%% in the 2-column matrix nzlistA{p,2} that
%% stores the row and column index of the nonzero elements
%% of Apk.
%% nzlistA{p,1}(k) = inf if nnz(Apk) exceeds given threshold.
%% nzlistAsum = px2 cell array.
%% nzlistA{p,1}(k) is the starting row index (in C convention)
%% in the 2-column matrix nzlistA{p,2} that
%% stores the row and column index of the nonzero elements
%% of Apk that are not already present
%% in the combined list from Ap1+...Ap,k-1.
%% nzlistAy = px1 cell array.
%% nzlistAy{p} is a 2-column matrix that stores the
%% row and column index of the nonzero elements of
%% Ap,1+.... Ap,m.
%% nzlistAy{p} = inf if the number of nonzero elements
%% exceeds a given threshold.
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%***********************************************************************
function [isspA,nzlistA,nzlistAsum,isspAy,nzlistAy] = nzlist(blk,At,par)
spdensity = par.spdensity;
smallblkdim = par.smallblkdim;
m = par.numcolAt;
%%
numblk = size(blk,1);
isspA = zeros(numblk,m);
nzlistA = cell(numblk,2); nzlistAsum = cell(numblk,2);
isspAy = zeros(numblk,1); nzlistAy = cell(numblk,1);
%%
for p = 1:size(blk,1)
pblk = blk(p,:);
if strcmp(pblk{1},'s') && ((max(pblk{2}) > smallblkdim) || (length(pblk{2}) <= 10))
numblk = length(pblk{2});
n = sum(pblk{2});
n2 = sum(pblk{2}.*pblk{2});
if (numblk == 1)
nztol = spdensity*n;
nztol2 = spdensity*n2/2;
else
nztol = spdensity*n/2;
nztol2 = spdensity*n2/4;
end
nzlist1 = zeros(1,m+1); nzlist2 = [];
nzlist3 = zeros(1,m+1); nzlist4 = []; breakyes = zeros(1,2);
Asum = sparse(n,n);
%%
m1 = size(At{p,1},2);
for k = 1:m1
Ak = mexsmat(blk,At,1,p,k);
nnzAk = nnz(Ak);
isspA(p,k) = (nnzAk < spdensity*n2) || (numblk > 1);
if ~all(breakyes)
[I,J] = find(abs(Ak) > 0);
%%
%% nonzero elements of Ak.
%%
if (breakyes(1) == 0);
if (nnzAk <= nztol)
idx = find(I<=J);
nzlist1(k+1) = nzlist1(k)+length(idx);
nzlist2 = [nzlist2; [I(idx), J(idx)] ]; %#ok
else
nzlist1(k+1:m+1) = inf*ones(1,m-k+1);
breakyes(1) = 1;
end
end
%%
%% nonzero elements of ||A1||+...+||Ak||.
%%
if (breakyes(2) == 0)
nztmp = zeros(length(I),1);
for t = 1:length(I);
i=I(t); j=J(t); nztmp(t)=Asum(i,j);
end
%% find new nonzero positions when Ak is added to Asum.
idx = find(nztmp == 0);
nzlist3(k+1) = nzlist3(k) + length(idx);
if (nzlist3(k+1) < nztol2);
nzlist4 = [ nzlist4; [I(idx), J(idx)] ]; %#ok
else
nzlist3(k+1:m+1) = inf*ones(1,m-k+1);
breakyes(2) = 1;
end
Asum = Asum+abs(Ak);
end
end
end
if (numblk == 1)
isspAy(p,1) = (nzlist1(m+1) < inf) || (nzlist3(m+1) < inf);
else
isspAy(p,1) = 1;
end
nzlistA{p,1} = nzlist1; nzlistA{p,2} = nzlist2;
nzlistAsum{p,1} = nzlist3; nzlistAsum{p,2} = nzlist4;
%%
%% nonzero elements of (A1*y1+...Am*ym).
%%
if (nzlist3(m+1) < inf);
if (length(pblk) > 2)
% m2 = length(pblk{3});
len = sum(pblk{3});
DD = spconvert([At{p,3}(:,2:4); len, len, 0]);
Asum = Asum + abs(At{p,2}*DD*At{p,2}');
end
[I,J] = find(Asum > 0);
if (length(I) < nztol2)
nzlistAy{p} = [I, J];
else
nzlistAy{p} = inf;
end
else
nzlistAy{p} = inf;
end
end
end
%%***********************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
detect_lblk.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/detect_lblk.m
| 4,228 |
utf_8
|
a69e3486a171d0169d9b62b749ed6cd8
|
%%*******************************************************************
%% detect_lblk: detect diagonal blocks in the SDP data.
%%
%% [blk,At,C,diagblkinfo,blockchange,parbarrier,X,Z] = ...
%% detect_lblk(blk,At,C,b,parbarrier,X,Z);
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%******************************************************************
function [blk,At,C,diagblkinfo,blockchange,parbarrier,X,Z] = ...
detect_lblk(blk,At,C,b,parbarrier,X,Z,printlevel)
if (nargin < 8); printlevel = 1; end
%%
%% Acum = abs(C) + sum_{k=1}^m abs(Ak)
%% but with diagonal elements removed.
%%
blkold = blk;
m = length(b);
ee = ones(m,1);
numdiagelt = 0;
numblknew = 0;
blockchange = zeros(size(blk,1),1);
Acum = cell(size(blk,1),1);
diagblkinfo = cell(size(blk,1),3);
for p=1:size(blk,1)
pblk = blk(p,:);
n = sum(pblk{2});
if strcmp(pblk{1},'s') && (length(pblk{2}) == 1) && (size(At{p,1},2)==m)
Acumtmp = smat(blk(p,:),abs(At{p})*ee,1) + abs(C{p});
Acum{p} = Acumtmp - spdiags(diag(Acumtmp),0,n,n);
rownorm = sqrt(sum(Acum{p}.*Acum{p}))';
idxdiag = find(rownorm < 1e-15);
if ~isempty(idxdiag)
blockchange(p) = 1;
numdiagelt = numdiagelt + length(idxdiag);
idxnondiag = setdiff((1:n)',idxdiag);
diagblkinfo{p,2} = idxdiag;
diagblkinfo{p,3} = idxnondiag(:);
if ~isempty(idxnondiag)
numblknew = numblknew + 1;
diagblkinfo{p,1} = numblknew;
end
else
numblknew = numblknew + 1;
diagblkinfo{p,1} = numblknew;
end
else
numblknew = numblknew + 1;
diagblkinfo{p,1} = numblknew;
end
end
%%
%% extract diagonal sub-blocks in nondiagonal blocks
%% into a single linear block
%%
if any(blockchange)
numblk = size(blkold,1);
idx_keepblk = [];
Atmp = cell(1,m);
Adiag = cell(1,m);
C(numblk+1,1) = cell(1,1);
Cdiag = []; Xdiag = []; Zdiag = [];
parbarrierdiag = [];
for p = 1:numblk
% n = sum(blkold{p,2});
if (blockchange(p)==1)
idxdiag = diagblkinfo{p,2};
idxnondiag = diagblkinfo{p,3};
if ~isempty(idxdiag);
blk{p,2} = length(idxnondiag);
len = length(idxdiag);
for k = 1:m;
Ak = mexsmat(blkold,At,1,p,k);
tmp = diag(Ak);
Atmp{k} = Ak(idxnondiag,idxnondiag);
Adiag{k} = [Adiag{k}; tmp(idxdiag)];
end
tmp = diag(C{p,1});
Cdiag = [Cdiag; tmp(idxdiag)]; %#ok
C{p,1} = C{p,1}(idxnondiag,idxnondiag);
At(p) = svec(blk(p,:),Atmp,1);
if (nargin >= 7)
parbarrierdiag = [parbarrierdiag, parbarrier{p}*ones(1,len)]; %#ok
tmp = diag(X{p,1});
Xdiag = [Xdiag; tmp(idxdiag)]; %#ok
tmp = diag(Z{p,1});
Zdiag = [Zdiag; tmp(idxdiag)]; %#ok
X{p,1} = X{p,1}(idxnondiag,idxnondiag);
Z{p,1} = Z{p,1}(idxnondiag,idxnondiag);
end
end
if ~isempty(idxnondiag)
idx_keepblk = [idx_keepblk, p]; %#ok
else
if (printlevel)
fprintf(' %2.0dth semidefinite block is actually diagonal\n',p);
end
end
else
idx_keepblk = [idx_keepblk, p]; %#ok
end
end
blk{numblk+1,1} = 'l';
blk{numblk+1,2} = numdiagelt;
C{numblk+1,1} = Cdiag;
At(numblk+1,1) = svec(blk(numblk+1,:),Adiag,1);
idx_keepblk = [idx_keepblk, numblk+1];
blk = blk(idx_keepblk,:);
C = C(idx_keepblk,:);
At = At(idx_keepblk,:);
if (nargin >= 7)
parbarrier{numblk+1,1} = parbarrierdiag;
X{numblk+1,1} = Xdiag;
Z{numblk+1,1} = Zdiag;
parbarrier = parbarrier(idx_keepblk);
X = X(idx_keepblk);
Z = Z(idx_keepblk);
end
end
%%******************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
gdcomp.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/gdcomp.m
| 4,877 |
utf_8
|
edb240000afc00b0bd8d14fdc4ab944c
|
%%*********************************************************************
%% gdcomp: Compute gd = 1/td in Equation (15) of the paper:
%%
%% R.M. Freund, F. Ordonez, and K.C. Toh,
%% Behavioral measures and their correlation with IPM iteration counts
%% on semi-definite programming problems,
%% Mathematical Programming, 109 (2007), pp. 445--475.
%%
%% [gd,info,yfeas,Zfeas,blk2,At2,C2,b2] = gdcomp(blk,At,C,b,OPTIONS,solveyes);
%%
%% yfeas,Zfeas: a dual feasible pair when gd is finite.
%% That is, if
%% Aty = Atyfun(blk,At,[],[],yfeas);
%% Rd = ops(C,'-',ops(Zfeas,'+',Aty));
%% then
%% ops(Rd,'norm') should be small.
%%
%%*********************************************************************
function [gd,info,yfeas,Zfeas,blk2,At2,C2,b2] = gdcomp(blk,At,C,b,OPTIONS,solveyes)
if (nargin < 6); solveyes = 1; end
if (nargin < 5)
OPTIONS = sqlparameters;
OPTIONS.vers = 1;
OPTIONS.gaptol = 1e-10;
OPTIONS.printlevel = 3;
end
if isempty(OPTIONS); OPTIONS = sqlparameters; end
if ~isfield(OPTIONS,'solver'); OPTIONS.solver = 'HSDsqlp'; end
if ~isfield(OPTIONS,'printlevel'); OPTIONS.printlevel = 3; end
if ~iscell(C); tmp = C; clear C; C{1} = tmp; end
%%
%% convert ublk to lblk
%%
% exist_ublk = 0;
for p = 1:size(blk,1)
pblk = blk(p,:);
if strcmp(pblk{1},'u');
% exist_ublk = 1;
fprintf('\n converting ublk into the difference of two non-negative vectors');
blk{p,1} = 'l'; blk{p,2} = 2*sum(blk{p,2});
At{p} = [At{p}; -At{p}];
C{p} = [C{p}; -C{p}];
end
end
%%
m = length(b);
blk2 = blk;
At2 = cell(size(blk,1),1);
C2 = cell(size(blk,1),1);
EE = cell(size(blk,1),1);
%%
%%
%%
dd = zeros(1,m);
alp = 0;
beta = 0;
for p = 1:size(blk,1)
pblk = blk(p,:);
n = sum(pblk{2});
if strcmp(pblk{1},'s')
C2{p,1} = sparse(n,n);
else
C2{p,1} = zeros(n,1);
end
dd = dd + sqrt(sum(At{p}.*At{p}));
beta = beta + norm(C{p},'fro');
alp = alp + sqrt(n);
end
alp = 1./max(1,alp);
beta = 1./max(1,beta);
dd = 1./max(1,dd);
%%
%% New multipliers in dual problem:
%% [v; tt; theta].
%%
D = spdiags(dd',0,m,m);
ss = 0; cc = 0; aa = zeros(1,m);
% exist_ublk = 0;
for p = 1:size(blk,1)
pblk = blk(p,:);
n = sum(pblk{2});
if strcmp(pblk{1},'s')
At2{p} = [At{p}*D, svec(pblk,alp*speye(n,n),1), -svec(pblk,beta*C{p},1)];
ss = ss + n;
cc = cc + trace(C{p});
aa = aa + svec(pblk,speye(n),1)'*At{p};
EE{p} = speye(n,n);
elseif strcmp(pblk{1},'q')
eq = zeros(n,1);
idx1 = 1+[0,cumsum(pblk{2})];
idx1 = idx1(1:length(idx1)-1);
eq(idx1) = ones(length(idx1),1);
At2{p} = [At{p}*D, 2*sparse(alp*eq), -sparse(beta*C{p})];
ss = ss + 2*length(pblk{2});
cc = cc + sum(C{p}(idx1));
aa = aa + eq'*At{p};
EE{p} = eq;
elseif strcmp(pblk{1},'l')
el = ones(n,1);
At2{p} = [At{p}*D, sparse(alp*el), -sparse(beta*C{p})];
ss = ss + n;
cc = cc + el'*C{p};
aa = aa + el'*At{p};
EE{p} = el;
elseif strcmp(pblk{1},'u')
At2{p} = [At{p}*D, sparse(n,1), -sparse(beta*C{p})];
% exist_ublk = 1;
EE{p} = sparse(n,1);
end
end
aa = aa.*dd;
cc = cc*beta;
%%
%% 4 additional inequality constraints in dual problem.
%%
numblk = size(blk,1);
blk2{numblk+1,1} = 'l'; blk2{numblk+1,2} = 4;
C2{numblk+1,1} = [1; 1; 0; 0];
At2{numblk+1,1} = [-aa, 0, cc;
zeros(1,m), 0, beta;
zeros(1,m), alp, -beta
zeros(1,m), -alp, 0];
At2{numblk+1} = sparse(At2{numblk+1});
b2 = [zeros(m,1); alp; 0];
%%
%% Solve SDP
%%
gd = []; info = []; yfeas = []; Zfeas = [];
if (solveyes)
if strcmp(OPTIONS.solver,'sqlp')
[X0,y0,Z0] = infeaspt(blk2,At2,C2,b2,2,100);
[obj,X,y,Z,info] = sqlp(blk2,At2,C2,b2,OPTIONS,X0,y0,Z0); %#ok
elseif strcmp(OPTIONS.solver,'HSDsqlp');
[obj,X,y,Z,info] = HSDsqlp(blk2,At2,C2,b2,OPTIONS); %#ok
else
[obj,X,y,Z,info] = sdpt3(blk2,At2,C2,b2,OPTIONS); %#ok
end
tt = alp*abs(y(m+1)); theta = beta*abs(y(m+2));
yfeas = D*y(1:m)/theta;
Zfeas = ops(ops(Z(1:numblk),'+',EE,tt),'/',theta);
%%
if (obj(2) > 0) || (abs(obj(2)) < 1e-8)
gd = 1/abs(obj(2));
elseif (obj(1) > 0)
gd = 1/obj(1);
else
gd = 1/exp(mean(log(abs(obj))));
end
err = max(info.dimacs([1,3,6]));
if (OPTIONS.printlevel)
fprintf('\n ******** gd = %3.2e, err = %3.1e\n',gd,err);
if (err > 1e-6);
fprintf('\n----------------------------------------------------')
fprintf('\n gd problem is not solved to sufficient accuracy');
fprintf('\n----------------------------------------------------\n')
end
end
end
%%*********************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
blkbarrier.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/blkbarrier.m
| 1,795 |
utf_8
|
77a6eb1f1708aa69217000d27735efa0
|
%%********************************************************************
%% blkbarrier: calculate
%% [-v(p)*logdet(X{p}), v(p)*logdet(Z{p}) + n*v(p)*(1-log(v(p)))]
%% [-v(p)*log(gam(X{p})), v(p)*log(gam(Z{p})) + v(p)]
%% [-v(p)*log(X{p}), v(p)*log(Z{p}) + n*v(p)*(1-log(v(p)))]
%%********************************************************************
function objadd = blkbarrier(blk,X,Z,Xchol,Zchol,v)
objadd = zeros(1,2); tmp = zeros(1,2);
for p = 1:size(blk,1)
pblk = blk(p,:);
vp = v{p};
idx = find(vp > 0);
if ~isempty(idx)
vpsub = vp(idx);
if size(vpsub,1) < size(vpsub,2); vpsub = vpsub'; end
if strcmp(pblk{1},'s')
ss = [0, cumsum(pblk{2})];
logdetX = 2*log(diag(Xchol{p}));
logdetZ = 2*log(diag(Zchol{p}));
logdetXsub = zeros(length(idx),1);
logdetZsub = zeros(length(idx),1);
for k = 1:length(idx)
idxtmp = ss(idx(k))+1:ss(idx(k)+1);
logdetXsub(k) = sum(logdetX(idxtmp));
logdetZsub(k) = sum(logdetZ(idxtmp));
end
tmp(1) = -sum(vpsub.*logdetXsub);
tmp(2) = sum(vpsub.*logdetZsub + (pblk{2}(idx)').*vpsub.*(1-log(vpsub)));
elseif strcmp(pblk{1},'q')
gamX = sqrt(qops(pblk,X{p},X{p},2));
gamZ = sqrt(qops(pblk,Z{p},Z{p},2));
tmp(1) = -sum(vpsub.*log(gamX(idx)));
tmp(2) = sum(vpsub.*log(gamZ(idx)) + vpsub);
elseif strcmp(pblk{1},'l')
logX = log(X{p}); logZ = log(Z{p});
tmp(1) = -sum(vpsub.*logX(idx));
tmp(2) = sum(vpsub.*logZ(idx) + vpsub.*(1-log(vpsub)));
end
objadd = objadd + tmp;
end
end
%%********************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
sqlpmain.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/sqlpmain.m
| 29,812 |
utf_8
|
97c549fe923480dc73e59887089d5656
|
%%*************************************************************************
%% sqlp: main solver
%%
%%*************************************************************************
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%*************************************************************************
function [obj,X,y,Z,info,runhist] = sqlpmain(blk,At,C,b,par,parbarrier,X0,y0,Z0)
global spdensity smallblkdim printlevel msg
global solve_ok use_LU exist_analytic_term numpertdiagschur
global schurfun schurfun_par
%%
% matlabversion = par.matlabversion;
isoctave = exist( 'OCTAVE_VERSION', 'builtin' );
if isoctave,
w1 = warning('off','Octave:nearly-singular-matrix');
else
w1 = warning('off','MATLAB:nearlySingularMatrix');
w2 = warning('off','MATLAB:singularMatrix');
end
vers = par.vers;
predcorr = par.predcorr;
gam = par.gam;
expon = par.expon;
gaptol = par.gaptol + ( par.gaptol == 0 );
steptol = par.steptol;
maxit = par.maxit;
printlevel = par.printlevel;
stoplevel = par.stoplevel;
scale_data = par.scale_data;
spdensity = par.spdensity;
rmdepconstr = par.rmdepconstr;
smallblkdim = par.smallblkdim;
schurfun = par.schurfun;
schurfun_par = par.schurfun_par;
ublksize = par.ublksize;
%%
tstart = clock;
X = X0; y = y0; Z = Z0;
for p = 1:size(blk,1)
if strcmp(blk{p,1},'u'); Z{p} = zeros(blk{p,2},1); end
end
%%
%%-----------------------------------------
%% convert unrestricted blk to linear blk.
%%-----------------------------------------
%%
convertlen = 0;
[blk,At,C,X,Z,u2lblk,ublkidx] = sqlpu2lblk(blk,At,C,X,Z,par,convertlen);
for p = 1:size(blk,1)
% pblk = blk(p,:);
if (u2lblk(p) == 1)
n = 2*blk{p,2};
blk{p,1} = 'l'; blk{p,2} = n;
parbarrier{p} = zeros(1,n);
At{p} = [At{p}; -At{p}];
% tau = max(1,norm(C{p}));
C{p} = [C{p}; -C{p}];
msg = 'convert ublk to lblk';
if (printlevel); fprintf(' *** %s',msg); end
b2 = 1 + abs(b');
normCtmp = 1+norm(C{p});
normAtmp = 1+sqrt(sum(At{p}.*At{p}));
if (n > 1000)
const = sqrt(n);
else
const = n;
end
if (par.startpoint == 1)
X{p} = const* max([1,b2./normAtmp]) *ones(n,1);
Z{p} = const* max([1,normAtmp/sqrt(n),normCtmp/sqrt(n)]) *ones(n,1);
X{p} = X{p}.*(1+1e-10*randmat(n,1,0,'u'));
Z{p} = Z{p}.*(1+1e-10*randmat(n,1,0,'u'));
else
const = max(abs(X{p})) + 100;
X{p} = [X{p}+const; const*ones(n/2,1)];
%%old: const = 100; Z{p} = [const*ones(n/2,1); const*ones(n/2,1)];
Z{p} = [abs(Z0{p}); abs(Z0{p})] + 1e-4;
end
end
end
%%-----------------------------------------
%% check whether {A1,...,Am} is
%% linearly independent.
%%-----------------------------------------
%%
m0 = length(b);
[At,b,y,indeprows,par.depconstr,feasible,par.AAt] = ...
checkdepconstr(blk,At,b,y,rmdepconstr);
if (~feasible)
obj = []; X = cell(size(blk,1),1); y = []; Z = cell(size(blk,1),1);
runhist = [];
msg = 'SQLP is not feasible';
if (printlevel); fprintf('\n %s \n',msg); end
return;
end
par.normAAt = norm(par.AAt,'fro');
%%
%%-----------------------------------------
%% scale SQLP data. Note: must be done only
%% after checkdepconstr
%%-----------------------------------------
%%
normA2 = 1+ops(At,'norm');
normb2 = 1+norm(b);
normC2 = 1+ops(C,'norm');
normX0 = 1+ops(X0,'norm');
normZ0 = 1+ops(Z0,'norm');
if (scale_data)
[At,C,b,normA,normC,normb,X,y,Z] = scaling(blk,At,C,b,X,y,Z);
else
normA = 1; normC = 1; normb = 1;
end
%%
%%-----------------------------------------
%% find the combined list of non-zero
%% elements of Aj, j = 1:k, for each k.
%% IMPORTANT NOTE: Ak, C are permuted.
%%-----------------------------------------
%%
par.numcolAt = length(b);
[At,C,X,Z,par.permA,par.permZ] = sortA(blk,At,C,b,X,Z);
[par.isspA,par.nzlistA,par.nzlistAsum,par.isspAy,par.nzlistAy] = nzlist(blk,At,par);
%%
%%-----------------------------------------
%% create an artifical non-negative block
%% for a purely log-barrier problem
%%-----------------------------------------
%%
numblkold = size(blk,1);
nn = 0;
for p = 1:size(blk,1);
pblk = blk(p,:);
idx = find(parbarrier{p}==0);
if ~isempty(idx);
if strcmp(pblk{1},'l')
nn = nn + length(idx);
elseif strcmp(pblk{1},'q')
nn = nn + sum(pblk{2}(idx));
elseif strcmp(pblk{1},'s')
nn = nn + sum(pblk{2}(idx));
end
end
end
if (nn==0)
analytic_prob = 1;
numblk = size(blk,1)+1;
blk{numblk,1} = 'l'; blk{numblk,2} = 1;
At{numblk,1} = sparse(1,length(b));
C{numblk,1} = 1;
X{numblk,1} = 1e3;
Z{numblk,1} = 1e3;
parbarrier{numblk,1} = 0;
u2lblk(numblk,1) = 0;
nn = nn + 1;
else
analytic_prob = 0;
end
%%
exist_analytic_term = 0;
for p = 1:size(blk,1);
if any(parbarrier{p} > 0),
exist_analytic_term = 1;
end
end
%%-----------------------------------------
%% initialization
%%-----------------------------------------
%%
EE = ops(blk,'identity');
normE2 = ops(EE,'norm'); Zpertold = 1;
for p = 1:size(blk,1)
% normCC(p) = 1+ops(C(p),'norm');
normEE(p) = 1+ops(EE(p),'norm'); %#ok
end
[Xchol,indef(1)] = blkcholfun(blk,X);
[Zchol,indef(2)] = blkcholfun(blk,Z);
if any(indef)
msg = 'stop: X or Z not positive definite';
if (printlevel); fprintf('\n %s\n',msg); end
info.termcode = -3;
info.msg1 = msg;
obj = []; X = cell(size(blk,1),1); y = []; Z = cell(size(blk,1),1);
runhist = [];
return;
end
AX = AXfun(blk,At,par.permA,X);
rp = b-AX;
ZpATy = ops(Z,'+',Atyfun(blk,At,par.permA,par.isspAy,y));
ZpATynorm = ops(ZpATy,'norm');
Rd = ops(C,'-',ZpATy);
objadd0 = 0;
if (scale_data)
for p = 1:size(blk,1)
pblk = blk(p,:);
objadd0 = objadd0 + sum(parbarrier{p}.*pblk{2})*log(normA{p});
end
end
objadd = blkbarrier(blk,X,Z,Xchol,Zchol,parbarrier) + objadd0;
obj = (normb*normC)*[blktrace(blk,C,X), b'*y] + objadd;
gap = (normb*normC)*blktrace(blk,X,Z) - diff(objadd);
relgap = gap/(1+sum(abs(obj)));
prim_infeas = norm(rp)/normb2;
dual_infeas = ops(Rd,'norm')/normC2;
infeas = max(prim_infeas,dual_infeas);
if (scale_data)
infeas_org(1) = prim_infeas*normb;
infeas_org(2) = dual_infeas*normC;
else
infeas_org = [0,0];
end
trXZ = blktrace(blk,X,Z,parbarrier);
if (nn > 0); mu = trXZ/nn; else mu = gap/ops(X,'getM'); end
normX = ops(X,'norm');
%%
termcode = 0; restart = 0;
pstep = 1; dstep = 1; pred_convg_rate = 1; corr_convg_rate = 1;
besttol = max( relgap, infeas );
homRd = inf; homrp = inf; dy = zeros(length(b),1);
msg = []; msg2 = []; msg3 = [];
runhist.pobj = obj(1);
runhist.dobj = obj(2);
runhist.gap = gap;
runhist.relgap = relgap;
runhist.pinfeas = prim_infeas;
runhist.dinfeas = dual_infeas;
runhist.infeas = infeas;
runhist.pstep = 0;
runhist.dstep = 0;
runhist.step = 0;
runhist.normX = normX;
runhist.cputime = etime(clock,tstart);
ttime.preproc = runhist.cputime;
ttime.pred = 0; ttime.pred_pstep = 0; ttime.pred_dstep = 0;
ttime.corr = 0; ttime.corr_pstep = 0; ttime.corr_dstep = 0;
ttime.pchol = 0; ttime.dchol = 0; ttime.misc = 0;
%%
%%-----------------------------------------
%% display parameters and initial info
%%-----------------------------------------
%%
if (printlevel >= 2)
fprintf('\n********************************************');
fprintf('***********************\n');
fprintf(' SDPT3: Infeasible path-following algorithms');
fprintf('\n********************************************');
fprintf('***********************\n');
[hh,mm,ss] = mytime(ttime.preproc);
if (printlevel>=3)
fprintf(' version predcorr gam expon scale_data\n');
if (vers == 1); fprintf(' HKM '); elseif (vers == 2); fprintf(' NT '); end
fprintf(' %1.0f %4.3f',predcorr,gam);
fprintf(' %1.0f %1.0f %1.0f\n',expon,scale_data);
fprintf('\nit pstep dstep pinfeas dinfeas gap')
fprintf(' prim-obj dual-obj cputime\n');
fprintf('------------------------------------------------');
fprintf('-------------------\n');
fprintf('%2.0f|%4.3f|%4.3f|%2.1e|%2.1e|',0,0,0,prim_infeas,dual_infeas);
fprintf('%2.1e|%- 7.6e %- 7.6e| %s:%s:%s|',gap,obj(1),obj(2),hh,mm,ss);
end
end
%%
%%---------------------------------------------------------------
%% start main loop
%%---------------------------------------------------------------
%%
param.termcode = termcode;
param.iter = 0;
param.obj = obj;
param.relgap = relgap;
param.prim_infeas = prim_infeas; param.dual_infeas = dual_infeas;
param.homRd = homRd; param.homrp = homrp;
param.AX = AX; param.ZpATynorm = ZpATynorm;
param.normA = normA;
param.normb = normb; param.normC = normC;
param.normX0 = normX0; param.normZ0 = normZ0;
param.m0 = m0; param.indeprows = indeprows;
param.prim_infeas_bad = 0;
param.dual_infeas_bad = 0;
param.prim_infeas_min = prim_infeas;
param.dual_infeas_min = dual_infeas;
param.gaptol = par.gaptol;
param.inftol = par.inftol;
param.maxit = maxit;
param.scale_data = scale_data;
param.printlevel = printlevel;
param.ublksize = ublksize;
Xbest = X; ybest = y; Zbest = Z;
%%
for iter = 1:maxit;
tstart = clock;
timeold = tstart;
update_iter = 0; breakyes = 0;
pred_slow = 0; corr_slow = 0; % step_short = 0;
par.parbarrier = parbarrier;
par.iter = iter;
par.obj = obj;
par.relgap = relgap;
par.pinfeas = prim_infeas;
par.dinfeas = dual_infeas;
par.rp = rp;
par.y = y;
par.dy = dy;
par.normX = normX;
par.ZpATynorm = ZpATynorm;
%%if (printlevel > 2); fprintf(' %2.1e',par.normX); end
if (iter == 1 || restart); Cpert = min(1,normC2/ops(EE,'norm')); end
if (runhist.dinfeas(1) > 1e-3) && (~exist_analytic_term) ...
&& (relgap > 1e-4)
if (par.normX > 5e3 && iter < 20)
Cpert = Cpert*0.5;
elseif (par.normX > 5e2 && iter < 20);
Cpert = Cpert*0.3;
else
Cpert = Cpert*0.1;
end
Rd = ops(Rd,'+',EE,Cpert);
%%if (printlevel > 2); fprintf('|%2.1e',Cpert); end
end
%%---------------------------------------------------------------
%% predictor step.
%%---------------------------------------------------------------
%%
if (predcorr)
sigma = 0;
else
sigma = 1-0.9*min(pstep,dstep);
if (iter == 1); sigma = 0.5; end;
end
sigmu = cell(size(blk,1),1);
for p = 1:size(blk,1)
sigmu{p} = max(sigma*mu, parbarrier{p}');
end
invXchol = cell(size(blk,1),1);
invZchol = ops(Zchol,'inv');
if (vers == 1);
[par,dX,dy,dZ,coeff,L,hRd] = ...
HKMpred(blk,At,par,rp,Rd,sigmu,X,Z,invZchol);
elseif (vers == 2);
[par,dX,dy,dZ,coeff,L,hRd] = ...
NTpred(blk,At,par,rp,Rd,sigmu,X,Z,Zchol,invZchol);
end
if (solve_ok <= 0)
msg = 'stop: difficulty in computing predictor directions';
if (printlevel); fprintf('\n %s',msg); end
runhist.pinfeas(iter+1) = runhist.pinfeas(iter);
runhist.dinfeas(iter+1) = runhist.dinfeas(iter);
runhist.relgap(iter+1) = runhist.relgap(iter);
runhist.cputime(iter+1) = etime(clock,tstart);
termcode = -4;
break; %% do not ues breakyes = 1
end
timenew = clock;
ttime.pred = ttime.pred + etime(timenew,timeold); timeold = timenew;
%%
%%-----------------------------------------
%% step-lengths for predictor step
%%-----------------------------------------
%%
if (gam == 0)
gamused = 0.9 + 0.09*min(pstep,dstep);
else
gamused = gam;
end
[Xstep,invXchol] = steplength(blk,X,dX,Xchol,invXchol);
pstep = min(1,gamused*full(Xstep));
timenew = clock;
ttime.pred_pstep = ttime.pred_pstep + etime(timenew,timeold); timeold = timenew;
Zstep = steplength(blk,Z,dZ,Zchol,invZchol);
dstep = min(1,gamused*full(Zstep));
trXZnew = trXZ + pstep*blktrace(blk,dX,Z,parbarrier) ...
+ dstep*blktrace(blk,X,dZ,parbarrier) ...
+ pstep*dstep*blktrace(blk,dX,dZ,parbarrier);
if (nn > 0); mupred = trXZnew/nn; else mupred = 1e-16; end
mupredhist(iter) = mupred; %#ok
timenew = clock;
ttime.pred_dstep = ttime.pred_dstep + etime(timenew,timeold); timeold = timenew;
%%
%%-----------------------------------------
%% stopping criteria for predictor step.
%%-----------------------------------------
%%
if (min(pstep,dstep) < steptol) && (stoplevel) && (iter > 10)
msg = 'stop: steps in predictor too short';
if (printlevel)
fprintf('\n %s',msg);
fprintf(': pstep = %3.2e, dstep = %3.2e\n',pstep,dstep);
end
runhist.cputime(iter+1) = etime(clock,tstart);
termcode = -2;
breakyes = 1;
end
if (~predcorr)
if (iter >= 2)
idx = max(2,iter-2) : iter;
pred_slow = all(mupredhist(idx)./mupredhist(idx-1) > 0.4);
idx = max(2,iter-5) : iter;
pred_convg_rate = mean(mupredhist(idx)./mupredhist(idx-1));
pred_slow = pred_slow + (mupred/mu > 5*pred_convg_rate);
end
if (max(mu,infeas) < 1e-6) && (pred_slow) && (stoplevel)
msg = 'stop: lack of progress in predictor';
if (printlevel)
fprintf('\n %s',msg);
fprintf(': mupred/mu = %3.2f, pred_convg_rate = %3.2f.',...
mupred/mu,pred_convg_rate);
end
runhist.cputime(iter+1) = etime(clock,tstart);
termcode = -2;
breakyes = 1;
else
update_iter = 1;
end
end
%%---------------------------------------------------------------
%% corrector step.
%%---------------------------------------------------------------
%%
if (predcorr) && (~breakyes)
step_pred = min(pstep,dstep);
if (mu > 1e-6)
if (step_pred < 1/sqrt(3));
expon_used = 1;
else
expon_used = max(expon,3*step_pred^2);
end
else
expon_used = max(1,min(expon,3*step_pred^2));
end
if (nn==0)
sigma = 0.2;
elseif (mupred < 0)
sigma = 0.8;
else
sigma = min(1, (mupred/mu)^expon_used);
end
sigmu = cell(size(blk,1),1);
for p = 1:size(blk,1)
sigmu{p} = max(sigma*mu, parbarrier{p}');
end
if (vers == 1)
[dX,dy,dZ] = HKMcorr(blk,At,par,rp,Rd,sigmu,hRd,...
dX,dZ,coeff,L,X,Z);
elseif (vers == 2)
[dX,dy,dZ] = NTcorr(blk,At,par,rp,Rd,sigmu,hRd,...
dX,dZ,coeff,L,X,Z);
end
if (solve_ok <= 0)
msg = 'stop: difficulty in computing corrector directions';
if (printlevel); fprintf('\n %s',msg); end
runhist.pinfeas(iter+1) = runhist.pinfeas(iter);
runhist.dinfeas(iter+1) = runhist.dinfeas(iter);
runhist.relgap(iter+1) = runhist.relgap(iter);
runhist.cputime(iter+1) = etime(clock,tstart);
termcode = -4;
break; %% do not ues breakyes = 1
end
timenew = clock;
ttime.corr = ttime.corr + etime(timenew,timeold); timeold = timenew;
%%
%%-----------------------------------
%% step-lengths for corrector step
%%-----------------------------------
%%
if (gam == 0)
gamused = 0.9 + 0.09*min(pstep,dstep);
else
gamused = gam;
end
Xstep = steplength(blk,X,dX,Xchol,invXchol);
pstep = min(1,gamused*full(Xstep));
timenew = clock;
ttime.corr_pstep = ttime.corr_pstep+etime(timenew,timeold); timeold = timenew;
Zstep = steplength(blk,Z,dZ,Zchol,invZchol);
dstep = min(1,gamused*full(Zstep));
trXZnew = trXZ + pstep*blktrace(blk,dX,Z,parbarrier) ...
+ dstep*blktrace(blk,X,dZ,parbarrier)...
+ pstep*dstep*blktrace(blk,dX,dZ,parbarrier);
if (nn > 0); mucorr = trXZnew/nn; else mucorr = 1e-16; end
timenew = clock;
ttime.corr_dstep = ttime.corr_dstep+etime(timenew,timeold); timeold = timenew;
%%
%%-----------------------------------------
%% stopping criteria for corrector step
%%-----------------------------------------
if (iter >= 2)
idx = max(2,iter-2) : iter;
corr_slow = all(runhist.gap(idx)./runhist.gap(idx-1) > 0.8);
idx = max(2,iter-5) : iter;
corr_convg_rate = mean(runhist.gap(idx)./runhist.gap(idx-1));
corr_slow = corr_slow + (mucorr/mu > max(min(1,5*corr_convg_rate),0.8));
end
if (max(relgap,infeas) < 1e-6) && (iter > 20) ...
&& (corr_slow > 1) && (stoplevel)
msg = 'stop: lack of progress in corrector';
if (printlevel)
fprintf('\n %s',msg);
fprintf(': mucorr/mu = %3.2f, corr_convg_rate = %3.2f',...
mucorr/mu,corr_convg_rate);
end
runhist.cputime(iter+1) = etime(clock,tstart);
termcode = -2;
breakyes = 1;
else
update_iter = 1;
end
end
%%---------------------------------------------------------------
%% udpate iterate
%%---------------------------------------------------------------
indef = [1,1];
if (update_iter)
for t = 1:5
[Xchol,indef(1)] = blkcholfun(blk,ops(X,'+',dX,pstep));
timenew = clock;
ttime.pchol = ttime.pchol + etime(timenew,timeold); timeold = timenew;
if (indef(1)); pstep = 0.8*pstep; else break; end
end
if (t > 1); pstep = gamused*pstep; end
for t = 1:5
[Zchol,indef(2)] = blkcholfun(blk,ops(Z,'+',dZ,dstep));
timenew = clock;
ttime.dchol = ttime.dchol + etime(timenew,timeold); timeold = timenew;
if (indef(2)); dstep = 0.8*dstep; else break; end
end
if (t > 1); dstep = gamused*dstep; end
%%-------------------------------------------
AXtmp = AX + pstep*AXfun(blk,At,par.permA,dX);
prim_infeasnew = norm(b-AXtmp)/normb2;
if (relgap < 5*infeas); alpha = 1e2; else alpha = 1e3; end
if any(indef)
if indef(1); msg = 'stop: X not positive definite'; end
if indef(2); msg = 'stop: Z not positive definite'; end
if (printlevel); fprintf('\n %s',msg); end
termcode = -3;
breakyes = 1;
elseif (prim_infeasnew > max([1e-8,relgap,20*prim_infeas]) && iter > 10) ...
|| (prim_infeasnew > max([1e-7,1e3*prim_infeas,0.1*relgap]) && relgap < 1e-2) ...
|| (prim_infeasnew > alpha*max([1e-9,param.prim_infeas_min]) ...
&& (prim_infeasnew > max([3*prim_infeas,0.1*relgap])) ...
&& (iter > 25) && (dual_infeas < 1e-6) && (relgap < 0.1)) ...
|| ((prim_infeasnew > 1e3*prim_infeas && prim_infeasnew > 1e-12) ...
&& (max(relgap,dual_infeas) < 1e-8))
if (stoplevel)
msg = 'stop: primal infeas has deteriorated too much';
if (printlevel); fprintf('\n %s, %2.1e',msg,prim_infeasnew); end
termcode = -7;
breakyes = 1;
end
elseif (trXZnew > 1.05*runhist.gap(iter)) && (~exist_analytic_term) ...
&& ((infeas < 1e-5) && (relgap < 1e-4) && (iter > 20) ...
|| (max(infeas,relgap) < 1e-7) && (iter > 10))
if (stoplevel)
msg = 'stop: progress in duality gap has deteriorated';
if (printlevel); fprintf('\n %s, %2.1e',msg,trXZnew); end
termcode = -8;
breakyes = 1;
end
else
X = ops(X,'+',dX,pstep);
y = y + dstep*dy;
Z = ops(Z,'+',dZ,dstep);
end
end
%%---------------------------------------------------------------
%% adjust linear blk arising from unrestricted blk
%%---------------------------------------------------------------
if (~breakyes)
for p = 1:size(blk,1)
if (u2lblk(p) == 1)
len = blk{p,2}/2;
xtmp = min(X{p}(1:len),X{p}(len+1:2*len));
alpha = 0.8;
X{p}(1:len) = X{p}(1:len) - alpha*xtmp;
X{p}(len+1:2*len) = X{p}(len+1:2*len) - alpha*xtmp;
if (mu < 1e-4) %% old: (mu < 1e-7)
Z{p} = 0.5*mu./max(1,X{p}); %% good to keep this step
else
ztmp = min(1,max(Z{p}(1:len),Z{p}(len+1:2*len)));
if (dual_infeas > 1e-4 && dstep < 0.2)
beta = 0.3;
else
beta = 0.0;
end
%% important to set beta = 0 at later stage.
Z{p}(1:len) = Z{p}(1:len) + beta*ztmp;
Z{p}(len+1:2*len) = Z{p}(len+1:2*len) + beta*ztmp;
end
end
end
end
%%--------------------------------------------------
%% perturb Z: do this step before checking for break
%%--------------------------------------------------
if (~breakyes) && (~exist_analytic_term)
trXZtmp = blktrace(blk,X,Z);
trXE = blktrace(blk,X,EE);
Zpert = max(1e-12,0.2*min(relgap,prim_infeas)).*normC2./normE2;
Zpert = min(Zpert,0.1*trXZtmp./trXE);
Zpert = min([1,Zpert,1.5*Zpertold]);
if (infeas < 0.1)
Z = ops(Z,'+',EE,Zpert);
[Zchol,indef(2)] = blkcholfun(blk,Z);
if any(indef(2))
msg = 'stop: Z not positive definite';
if (printlevel); fprintf('\n %s',msg); end
termcode = -3;
breakyes = 1;
end
%%if (printlevel > 2); fprintf(' %2.1e',Zpert); end
end
Zpertold = Zpert;
end
%%---------------------------------------------------------------
%% compute rp, Rd, infeasibities, etc
%%---------------------------------------------------------------
%%
AX = AXfun(blk,At,par.permA,X);
rp = b-AX;
ZpATy = ops(Z,'+',Atyfun(blk,At,par.permA,par.isspAy,y));
ZpATynorm = ops(ZpATy,'norm');
Rd = ops(C,'-',ZpATy);
objadd = blkbarrier(blk,X,Z,Xchol,Zchol,parbarrier) + objadd0;
obj = (normb*normC)*[blktrace(blk,C,X), b'*y] + objadd;
gap = (normb*normC)*blktrace(blk,X,Z) - diff(objadd);
relgap = gap/(1+sum(abs(obj)));
prim_infeas = norm(rp)/normb2;
dual_infeas = ops(Rd,'norm')/normC2;
infeas = max(prim_infeas,dual_infeas);
if (scale_data)
infeas_org(1) = prim_infeas*normb;
infeas_org(2) = dual_infeas*normC;
end
homRd = inf; homrp = inf;
if (ops(parbarrier,'norm') == 0)
if (obj(2) > 0); homRd = ZpATynorm/(obj(2)); end
if (obj(1) < 0); homrp = norm(AX)/(-obj(1))/(normC); end
end
trXZ = blktrace(blk,X,Z,parbarrier);
if (nn > 0); mu = trXZ/nn; else mu = gap/ops(X,'getM'); end
normX = ops(X,'norm');
%%
runhist.pobj(iter+1) = obj(1);
runhist.dobj(iter+1) = obj(2);
runhist.gap(iter+1) = gap;
runhist.relgap(iter+1) = relgap;
runhist.pinfeas(iter+1) = prim_infeas;
runhist.dinfeas(iter+1) = dual_infeas;
runhist.infeas(iter+1) = infeas;
runhist.pstep(iter+1) = pstep;
runhist.dstep(iter+1) = dstep;
runhist.step(iter+1) = min(pstep,dstep);
runhist.normX(iter+1) = normX;
runhist.cputime(iter+1) = etime(clock,tstart);
timenew = clock;
ttime.misc = ttime.misc + etime(timenew,timeold); % timeold = timenew;
[hh,mm,ss] = mytime(sum(runhist.cputime));
if (printlevel>=3)
fprintf('\n%2.0f|%4.3f|%4.3f',iter,pstep,dstep);
fprintf('|%2.1e|%2.1e|%2.1e|',prim_infeas,dual_infeas,gap);
fprintf('%- 7.6e %- 7.6e| %s:%s:%s|',obj(1),obj(2),hh,mm,ss);
end
%%--------------------------------------------------
%% check convergence
%%--------------------------------------------------
param.use_LU = use_LU;
param.stoplevel = stoplevel;
param.termcode = termcode;
param.iter = iter;
param.obj = obj;
param.gap = gap;
param.relgap = relgap;
param.prim_infeas = prim_infeas;
param.dual_infeas = dual_infeas;
param.mu = mu;
param.homRd = homRd;
param.homrp = homrp;
param.AX = AX;
param.ZpATynorm = ZpATynorm;
param.normX = ops(X,'norm');
param.normZ = ops(Z,'norm');
param.numpertdiagschur = numpertdiagschur;
if (~breakyes)
[param,breakyes,restart,msg2] = sqlpcheckconvg(param,runhist);
end
if (restart)
[X,y,Z] = infeaspt(blk,At,C,b,2,1e5);
rp = b-AXfun(blk,At,par.permA,X);
ZpATy = ops(Z,'+',Atyfun(blk,At,par.permA,par.isspAy,y));
Rd = ops(C,'-',ZpATy);
trXZ = blktrace(blk,X,Z,parbarrier);
mu = trXZ/nn;
gap = (normb*normC)*blktrace(blk,X,Z) - diff(objadd);
prim_infeas = norm(rp)/normb2;
dual_infeas = ops(Rd,'norm')/normC2;
infeas = max(prim_infeas,dual_infeas);
[Xchol,indef(1)] = blkcholfun(blk,X);
[Zchol,indef(2)] = blkcholfun(blk,Z); %#ok
stoplevel = 3;
end
%%--------------------------------------------------
%% check for break
%%--------------------------------------------------
newtol = max(relgap,infeas);
update_best(iter+1) = ~( newtol >= besttol ); %#ok
if update_best(iter+1),
Xbest = X; ybest = y; Zbest = Z;
besttol = newtol;
end
if besttol < 1e-4 && ~any(update_best(max(1,iter-1):iter+1))
msg = 'lack of progress in infeas';
if (printlevel); fprintf('\n %s',msg); end
termcode = -9;
breakyes = 1;
end
if (breakyes); break; end
end
%%---------------------------------------------------------------
%% end of main loop
%%---------------------------------------------------------------
%%
use_bestiter = 1;
if (use_bestiter) && (param.termcode <= 0)
X = Xbest; y = ybest; Z = Zbest;
Xchol = blkcholfun(blk,X);
Zchol = blkcholfun(blk,Z);
AX = AXfun(blk,At,par.permA,X);
rp = b-AX;
ZpATy = ops(Z,'+',Atyfun(blk,At,par.permA,par.isspAy,y));
Rd = ops(C,'-',ZpATy);
objadd = blkbarrier(blk,X,Z,Xchol,Zchol,parbarrier) + objadd0;
obj = (normb*normC)*[blktrace(blk,C,X), b'*y] + objadd;
gap = (normb*normC)*blktrace(blk,X,Z) - diff(objadd);
relgap = gap/(1+sum(abs(obj)));
prim_infeas = norm(rp)/normb2;
dual_infeas = ops(Rd,'norm')/normC2;
infeas = max(prim_infeas,dual_infeas);
runhist.pobj(iter+1) = obj(1);
runhist.dobj(iter+1) = obj(2);
runhist.gap(iter+1) = gap;
runhist.relgap(iter+1) = relgap;
runhist.pinfeas(iter+1) = prim_infeas;
runhist.dinfeas(iter+1) = dual_infeas;
runhist.infeas(iter+1) = infeas;
end
%%---------------------------------------------------------------
%% unscale and produce infeasibility certificates if appropriate
%%---------------------------------------------------------------
if (iter >= 1)
[X,y,Z,termcode,resid,reldist,msg3] = ...
sqlpmisc(blk,At,C,b,X,y,Z,par.permZ,param);
end
%%---------------------------------------------------------------
%% recover unrestricted blk from linear blk
%%---------------------------------------------------------------
%%
for p = 1:size(blk,1)
if (u2lblk(p) == 1)
n = blk{p,2}/2;
X{p} = X{p}(1:n)-X{p}(n+1:2*n);
Z{p} = Z{p}(1:n);
end
end
for p = 1:size(ublkidx,1)
if ~isempty(ublkidx{p,2})
n0 = ublkidx{p,1}; idxB = setdiff((1:n0)',ublkidx{p,2});
tmp = zeros(n0,1); tmp(idxB) = X{p}; X{p} = tmp;
tmp = zeros(n0,1); tmp(idxB) = Z{p}; Z{p} = tmp;
end
end
if (analytic_prob)
X = X(1:numblkold); Z = Z(1:numblkold);
end
%%---------------------------------------------------------------
%% print summary
%%---------------------------------------------------------------
%%
maxC = 1+ops(ops(C,'abs'),'max');
maxb = 1+max(abs(b));
if (scale_data)
dimacs = [infeas_org(1)*normb2/maxb; 0; infeas_org(2)*normC2/maxC; 0];
else
dimacs = [prim_infeas*normb2/maxb; 0; dual_infeas*normC2/maxC; 0];
end
dimacs = [dimacs; [-diff(obj); gap]/(1+sum(abs(obj)))];
info.dimacs = dimacs;
info.termcode = termcode;
info.iter = iter;
info.obj = obj;
info.gap = gap;
info.relgap = relgap;
info.pinfeas = prim_infeas;
info.dinfeas = dual_infeas;
info.cputime = sum(runhist.cputime);
info.time = ttime;
info.resid = resid;
info.reldist = reldist;
info.normX = ops(X,'norm');
info.normy = norm(y);
info.normZ = ops(Z,'norm');
info.normb = normb2; info.maxb = maxb;
info.normC = normC2; info.maxC = maxC;
info.normA = normA2;
info.msg1 = msg;
info.msg2 = msg2;
info.msg3 = msg3;
sqlpsummary(info,ttime,infeas_org,printlevel);
if isoctave,
warning(w1.state,w1.identifier);
else
warning(w2.state,w2.identifier);
warning(w1.state,w1.identifier);
end
%%*****************************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
HKMpred.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/HKMpred.m
| 2,818 |
utf_8
|
da0e8d9efacd9a7cebaae5ea2ad63de9
|
%%*******************************************************************
%% HKMpred: Compute (dX,dy,dZ) for the H..K..M direction.
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%*******************************************************************
function [par,dX,dy,dZ,coeff,L,hRd] = ...
HKMpred(blk,At,par,rp,Rd,sigmu,X,Z,invZchol)
global schurfun schurfun_par
%%
%% compute HKM scaling
%%
Zinv = cell(size(blk,1),1); dd = cell(size(blk,1),1);
gamx = cell(size(blk,1),1); gamz = cell(size(blk,1),1);
for p = 1:size(blk,1)
pblk = blk(p,:);
n = sum(pblk{2});
numblk = length(pblk{2});
if strcmp(pblk{1},'l')
Zinv{p} = 1./Z{p};
dd{p} = X{p}./Z{p}; %% do not add perturbation, it badly affects cre-a
elseif strcmp(pblk{1},'q')
gaptmp = qops(pblk,X{p},Z{p},1);
gamz2 = qops(pblk,Z{p},Z{p},2);
gamz{p} = sqrt(gamz2);
Zinv{p} = qops(pblk,-1./gamz2,Z{p},4);
dd{p} = qops(pblk,gaptmp./gamz2,ones(n,1),4);
elseif strcmp(pblk{1},'s')
if (numblk == 1)
Zinv{p} = Prod2(pblk,full(invZchol{p}),invZchol{p}',1);
%% to fix the anonmaly when Zinv has very small elements
if (par.iter==2 || par.iter==3) && ~issparse(Zinv{p});
Zinv{p} = Zinv{p} + 1e-16;
end
else
Zinv{p} = Prod2(pblk,invZchol{p},invZchol{p}',1);
end
end
end
par.Zinv = Zinv; par.gamx = gamx; par.gamz = gamz; par.dd = dd;
%%
%% compute schur matrix
%%
m = length(rp);
schur = sparse(m,m);
UU = []; EE = []; Afree = [];
%%
for p = 1:size(blk,1)
pblk = blk(p,:);
if strcmp(pblk{1},'l')
[schur,UU,EE] = schurmat_lblk(blk,At,par,schur,UU,EE,p,par.dd);
elseif strcmp(pblk{1},'q');
[schur,UU,EE] = schurmat_qblk(blk,At,par,schur,UU,EE,p,par.dd,par.Zinv,X);
elseif strcmp(pblk{1},'s')
if isempty(schurfun{p})
schur = schurmat_sblk(blk,At,par,schur,p,X,par.Zinv);
elseif ischar(schurfun{p})
if ~isempty(par.permZ{p})
Zpinv = Zinv{p}(par.permZ{p},par.permZ{p});
Xp = X{p}(par.permZ{p},par.permZ{p});
else
Xp = X{p};
Zpinv = Zinv{p};
end
schurtmp = feval(schurfun{p},Xp,Zpinv,schurfun_par(p,:));
schur = schur + schurtmp;
end
elseif strcmp(pblk{1},'u')
Afree = [Afree, At{p}']; %#ok
end
end
%%
%% compute rhs
%%
[rhs,EinvRc,hRd] = HKMrhsfun(blk,At,par,X,Z,rp,Rd,sigmu);
%%
%% solve linear system
%%
[xx,coeff,L] = linsysolve(par,schur,UU,Afree,EE,rhs);
%%
%% compute (dX,dZ)
%%
[dX,dy,dZ] = HKMdirfun(blk,At,par,Rd,EinvRc,X,xx,m);
%%*******************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
read_sdpa.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/read_sdpa.m
| 7,591 |
utf_8
|
211ea10474df1ffe50a0c5456e1cbe41
|
%%*******************************************************************
%% Read in a problem in SDPA sparse format.
%%
%% [blk,At,C,b] = read_sdpa(fname)
%%
%% Input: fname = name of the file containing SDP data in
%% SDPA foramt.
%% Important: the data is assumed to contain only
%% semidefinite and linear blocks.
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%******************************************************************
function [blk,At,C,b] = read_sdpa(fname)
%%
%% Open the file for input
%%
compressed = 0;
if exist(fname,'file')
fid = fopen(fname,'r');
elseif exist([fname,'.Z'],'file');
compressed = 1;
unix(['uncompress ',fname,'.Z']);
fid = fopen(fname,'r');
elseif exist([fname,'.gz'],'file');
compressed = 2;
unix(['gunzip ',fname,'.gz']);
fid = fopen(fname,'r');
else
fprintf('*** Problem not found, please specify the correct path or problem name. \n');
blk = []; At = []; C = []; b = [];
return;
end
%%
%% Clean up special characters and comments from the file
%%
[datavec,count] = fscanf(fid,'%c'); %#ok
linefeeds = strfind(datavec,char(10));
comment_chars = '*"=';
cumidx = [];
for i=1:length(comment_chars)
idx = strfind(datavec,comment_chars(i));
cumidx = [cumidx,idx]; %#ok
end
for j=length(cumidx):-1:1
if (cumidx(j)==1) || (strcmp(datavec(cumidx(j)-1),char(10)))
datavec(cumidx(j):linefeeds(find(cumidx(j)<linefeeds,1,'first')))='';
else
datavec(cumidx(j):linefeeds(find(cumidx(j)<linefeeds,1,'first'))-1)='';
end
end
special_chars = ',{}()';
cumidx=[];
for i=1:length(special_chars)
idx = strfind(datavec,special_chars(i));
cumidx = [cumidx,idx]; %#ok
end
datavec(cumidx) = blanks(length(cumidx));
clear linefeeds;
%%
%% Close the file
%%
fclose(fid);
if compressed==1; unix(['compress ',fname]); end;
if compressed==2; unix(['gzip ',fname]); end;
%%
%% Next, read in basic problem size parameters.
%%
datavec = sscanf(datavec,'%f');
if size(datavec,1) < size(datavec,2); datavec = datavec'; end;
m = datavec(1);
numblk = datavec(2);
blksize = datavec(3:numblk+2);
if size(blksize,1) > size(blksize,2); blksize = blksize'; end
%%
%% Get input b.
%%
idxstrt = 2+numblk;
b = datavec(idxstrt+1:idxstrt+m);
idxstrt = idxstrt+m;
b = -b;
%%
%% Construct blk
%%
deblksize = 100;
spblkidxtmp = find( (blksize>1) & (blksize < deblksize) );
spblkidxtmp = sort(spblkidxtmp);
deblkidx = find( (blksize<=1) | (blksize >= deblksize) );
denumblk = length(deblkidx);
linblkidx = zeros(1,denumblk);
for p = 1:denumblk
n = blksize(deblkidx(p));
if (n > 1);
blk{p,1} = 's'; blk{p,2} = n; %#ok
n2 = n*(n+1)/2;
At{p,1} = sparse(n2,m); %#ok
C{p,1} = sparse(n,n); %#ok
else
linblkidx(p) = p;
blk{p,1} = 'l'; blk{p,2} = abs(n); %#ok
At{p,1} = sparse(abs(n),m); %#ok
C{p,1} = sparse(abs(n),1); %#ok
end
end
if ~isempty(spblkidxtmp)
maxnumblk = 200;
spnumblk = ceil(length(spblkidxtmp)/maxnumblk);
for q = 1:spnumblk
if (q < spnumblk)
spblkidxall{q} = spblkidxtmp([(q-1)*maxnumblk+1: q*maxnumblk]); %#ok
else
spblkidxall{q} = spblkidxtmp([(q-1)*maxnumblk+1: length(spblkidxtmp)]); %#ok
end
tmp = blksize(spblkidxall{q});
blk{denumblk+q,1} = 's'; %#ok
blk{denumblk+q,2} = tmp; %#ok
n2 = sum(tmp.*(tmp+1))/2;
At{denumblk+q,1} = sparse(n2,m); %#ok
C{denumblk+q,1} = sparse(sum(tmp),sum(tmp)); %#ok
end
else
spnumblk = 0;
end
linblkidx(denumblk+1:denumblk+spnumblk) = 0;
%%
%% Construct single blocks of A,C
%%
len = length(datavec);
Y = reshape(datavec(idxstrt+1:len),5,(len-idxstrt)/5)';
clear datavec;
Y = sortrows(Y,[1 2]);
matidx = [0; find(diff(Y(:,1)) ~= 0); size(Y,1)];
%%
for k = 1:length(matidx)-1
idx = matidx(k)+1 : matidx(k+1);
Ytmp = Y(idx,1:5);
matno = Ytmp(1,1);
Ytmp2 = Ytmp(:,2);
for p = 1:denumblk
n = blksize(deblkidx(p));
idx = find(Ytmp2 == deblkidx(p));
ii = Ytmp(idx,3); jj = Ytmp(idx,4); vv =Ytmp(idx,5);
len = length(idx);
if (n > 1)
idxtmp = find(ii > jj);
if ~isempty(idxtmp);
tmp = jj(idxtmp);
jj(idxtmp) = ii(idxtmp); ii(idxtmp) = tmp;
end
tmp = -sparse(ii,jj,vv,n,n);
tmp = tmp + triu(tmp,1)';
else
tmp = -sparse(ii,ones(len,1),vv,abs(n),1);
end
if (matno == 0)
C{p,1} = tmp; %#ok
else
if (n > 1)
At{p,1}(:,matno) = svec(blk(p,:),tmp,1); %#ok
else
At{p,1}(:,matno) = tmp; %#ok
end
end
end
end
%%
%% Construct big sparse block of A,C
%%
if (spnumblk > 0)
Y1 = Y(:,1);
diffY1 = find(diff([-1; Y1; inf]));
for kk = 1:length(diffY1)-1
idx = diffY1(kk) : diffY1(kk+1)-1;
matno = Y1(diffY1(kk));
Ytmp = Y(idx,1:5);
Ytmp2 = Ytmp(:,2);
maxYtmp2 = Ytmp2(length(Ytmp2));
minYtmp2 = Ytmp2(1);
diffYtmp2 = Ytmp2(diff([-1; Ytmp2])~=0);
for q = 1:spnumblk
spblkidx = spblkidxall{q};
maxspblkidx = spblkidx(length(spblkidx));
minspblkidx = spblkidx(1);
count = 0;
if (minYtmp2 <= maxspblkidx) && (maxYtmp2 >= minspblkidx)
tmpblksize = blksize(spblkidx);
n = sum(tmpblksize);
cumspblksize = [0 cumsum(tmpblksize)];
n2 = sum(tmpblksize.*(tmpblksize+1))/2;
idx = zeros(n2,1); offset = zeros(n2,1);
for t = 1:length(diffYtmp2)
p = find(spblkidx == diffYtmp2(t));
if ~isempty(p)
idxtmp = find(Ytmp2 == spblkidx(p));
len = length(idxtmp);
idx(count+1:count+len) = idxtmp;
offset(count+1:count+len) = cumspblksize(p);
count = count + len;
end
end
idx = idx(1:count); offset = offset(1:count);
ii = Ytmp(idx,3)+offset; jj = Ytmp(idx,4)+offset; vv = Ytmp(idx,5);
idxtmp = find(ii > jj);
if ~isempty(idxtmp);
tmp = jj(idxtmp);
jj(idxtmp) = ii(idxtmp); ii(idxtmp) = tmp;
end
idxeq = find(ii==jj);
tmp = spconvert([ii jj -vv; jj ii -vv; n n 0]) ...
+ spconvert([ii(idxeq) jj(idxeq) vv(idxeq); n n 0]);
if (matno == 0)
C{denumblk+q,1} = tmp; %#ok
else
At{denumblk+q,1}(:,matno) = svec(blk(denumblk+q,:),tmp,1); %#ok
end
end
end
end
end
%%
%% put all linear blocks together as a single linear block
%%
idx = find(linblkidx);
if (length(idx) > 1)
sdpidx = find(linblkidx==0);
blktmp = 0; Atmp = []; Ctmp = [];
for k = 1:length(idx)
tmp = linblkidx(idx(k));
blktmp = blktmp+blk{tmp,2};
Atmp = [Atmp; At{tmp}]; %#ok
Ctmp = [Ctmp; C{tmp}]; %#ok
end
At = At(sdpidx); C = C(sdpidx); blk = blk(sdpidx,:);
len = length(sdpidx);
blk(2:len+1,:) = blk;
blk{1,1} = 'l'; blk{1,2} = blktmp;
At(2:len+1,1) = At; C(2:len+1,1) = C;
At{1,1} = Atmp; C{1,1} = Ctmp;
end
%%******************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
sortA.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/sortA.m
| 2,639 |
utf_8
|
c998ea7df87432b78f6c001d0bbc5318
|
%%*********************************************************************
%% sortA: sort columns of At{p} in ascending order according to the
%% number of nonzero elements.
%%
%% [At,C,b,X0,Z0,permA,permZ] = sortA(blk,At,C,b,X0,Z0);
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%*********************************************************************
function [At,C,X0,Z0,permA,permZ] = sortA(blk,At,C,b,X0,Z0)
global spdensity smallblkdim
%%
if isempty(spdensity); spdensity = 0.4; end
if isempty(smallblkdim); smallblkdim = 50; end
%%
numblk = size(blk,1);
m = length(b);
nnzA = zeros(numblk,m);
permA = kron(ones(numblk,1),1:m);
permZ = cell(size(blk,1),1);
%%
for p=1:size(blk,1)
pblk = blk(p,:);
n = sum(pblk{2});
% numblk = length(pblk{2});
if strcmp(pblk{1},'s') && (max(pblk{2}) > smallblkdim)
% n2 = sum(pblk{2}.*pblk{2});
n22 = sum(pblk{2}.*(pblk{2}+1))/2;
m1 = size(At{p,1},2);
if (length(pblk{2}) == 1)
tmp = abs(C{p}) + abs(Z0{p});
if (~isempty(At{p,1}))
tmp = tmp + smat(blk(p,:),abs(At{p,1})*ones(m1,1),1);
end
if (nnz(tmp) < spdensity*n22);
per = symamd(tmp);
invper = zeros(n,1); invper(per) = 1:n;
permZ{p} = invper;
if (~isempty(At{p,1}))
isspAt = issparse(At{p,1});
for k = 1:m1
Ak = smat(pblk,At{p,1}(:,k),1);
At{p,1}(:,k) = svec(pblk,Ak(per,per),isspAt);
end
end
C{p} = C{p}(per,per);
Z0{p} = Z0{p}(per,per);
X0{p} = X0{p}(per,per);
else
per = [];
end
if (length(pblk) > 2) && (~isempty(per))
% m2 = length(pblk{3});
P = spconvert([(1:n)', per', ones(n,1)]);
At{p,2} = P*At{p,2};
end
end
if ~isempty(At{p,1}) && (mexnnz(At{p,1}) < m*n22/2)
for k = 1:m1
Ak = At{p,1}(:,k);
nnzA(p,k) = length(find(abs(Ak) > eps));
end
[dummy,permAp] = sort(nnzA(p,1:m1)); %#ok
At{p,1} = At{p,1}(:,permAp);
permA(p,1:m1) = permAp;
end
elseif strcmp(pblk{1},'q') || strcmp(pblk{1},'l') || strcmp(pblk{1},'u');
if ~issparse(At{p,1});
At{p,1} = sparse(At{p,1});
end
end
end
%%*********************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
blkeig.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/blkeig.m
| 2,412 |
utf_8
|
97da97f8165585de45eae52a86e0f127
|
%%***************************************************************************
%% blkeig: compute eigenvalue decomposition of a cell array
%% whose contents are square matrices or the diagonal
%% of a diagonal matrix.
%%
%% [d,V] = blkeig(blk,X);
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%***************************************************************************
function [d,V] = blkeig(blk,X)
spdensity = 0.5;
if ~iscell(X);
if strcmp(blk{1},'s');
blktmp = blk{2};
if (length(blktmp) == 1);
if (nargout == 1);
d = eig(full(X));
elseif (nargout == 2);
[V,d] = eig(full(X));
d = diag(d);
end
else
if (nargout == 2);
V = sparse(length(X),length(X));
end
d = zeros(sum(blktmp),1);
xx = mexsvec(blk,X,0);
blktmp2 = blktmp.*(blktmp+1)/2;
s2 = [0, cumsum(blktmp2)];
blksub{1,1} = 's'; blksub{1,2} = 0;
s = [0, cumsum(blktmp)];
for i = 1:length(blktmp)
pos = s(i)+1 : s(i+1);
blksub{2} = blktmp(i);
Xsub = mexsmat(blksub,xx(s2(i)+1:s2(i+1)),0);
if (nargout == 1);
lam = eig(Xsub);
elseif (nargout == 2);
[evec,lam] = eig(Xsub);
lam = diag(lam);
V(pos,pos) = sparse(evec); %#ok
end
d(pos,1) = lam;
end
end
n2 = sum(blktmp.*blktmp);
if (nargout == 2);
if (nnz(V) <= spdensity*n2);
V = sparse(V);
else
V = full(V);
end
end
elseif strcmp(blk{1},'l');
if (nargout == 2);
V = ones(size(X)); d = X;
elseif (nargout == 1);
d = X;
end
end
else
if (nargout == 2);
V = cell(size(X)); d = cell(size(X));
for p = 1:size(blk,1);
[d{p},V{p}] = blkeig(blk(p,:),X{p});
end
elseif (nargout == 1);
d = cell(size(X));
for p = 1:size(blk,1);
d{p} = blkeig(blk(p,:),X{p});
end
end
end
%%***************************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
HKMrhsfun.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/HKMrhsfun.m
| 3,358 |
utf_8
|
b1e6a8305128af799634b9ef7324cfeb
|
%%*******************************************************************
%% HKMrhsfun: compute the right-hand side vector of the
%% Schur complement equation for the HKM direction.
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%*******************************************************************
function [rhs,EinvRc,hRd] = HKMrhsfun(blk,At,par,X,Z,rp,Rd,sigmu,hRd,dX,dZ)
m = length(rp);
if (nargin > 8)
corrector = 1;
else
corrector = 0;
hRd = zeros(m,1);
end
hEinvRc = zeros(m,1);
EinvRc = cell(size(blk,1),1);
rhsfree = [];
%%
for p = 1:size(blk,1)
pblk = blk(p,:);
n = sum(pblk{2});
if strcmp(pblk{1},'l')
if iscell(sigmu)
EinvRc{p} = sigmu{p}./Z{p} -X{p};
else
EinvRc{p} = sigmu./Z{p} -X{p};
end
Rq = sparse(n,1);
if (corrector) && (norm(par.parbarrier{p})==0)
Rq = dX{p}.*dZ{p}./Z{p};
else
tmp = par.dd{p}.*Rd{p};
tmp2 = mexMatvec(At{p},tmp,1);
hRd = hRd + tmp2;
end
EinvRc{p} = EinvRc{p} - Rq;
tmp2 = mexMatvec(At{p,1},EinvRc{p},1);
hEinvRc = hEinvRc + tmp2;
elseif strcmp(pblk{1},'q')
if iscell(sigmu)
EinvRc{p} = qops(pblk,sigmu{p},par.Zinv{p},3) -X{p};
else
EinvRc{p} = sigmu*par.Zinv{p} -X{p};
end
Rq = sparse(n,1);
if (corrector) && (norm(par.parbarrier{p})==0)
ff{p} = qops(pblk,1./par.gamz{p},Z{p},3); %#ok
hdx = qops(pblk,par.gamz{p},ff{p},5,dX{p});
hdz = qops(pblk,par.gamz{p},ff{p},6,dZ{p});
hdxdz = Arrow(pblk,hdx,hdz);
Rq = qops(pblk,par.gamz{p},ff{p},6,hdxdz);
else
tmp = par.dd{p}.*Rd{p} ...
+ qops(pblk,qops(pblk,Rd{p},par.Zinv{p},1),X{p},3) ...
+ qops(pblk,qops(pblk,Rd{p},X{p},1),par.Zinv{p},3);
tmp2 = mexMatvec(At{p,1},tmp,1);
hRd = hRd + tmp2;
end
EinvRc{p} = EinvRc{p} - Rq;
tmp2 = mexMatvec(At{p,1},EinvRc{p},1);
hEinvRc = hEinvRc + tmp2;
elseif strcmp(pblk{1},'s')
if iscell(sigmu)
%%ss = [0,cumsum(pblk{2})];
%%sigmuvec = zeros(n,1);
%%for k = 1:length(pblk{2});
%% sigmuvec(ss(k)+1:ss(k+1)) = sigmu{p}(k)*ones(pblk{2}(k),1);
%%end
sigmuvec = mexexpand(pblk{2},sigmu{p});
EinvRc{p} = par.Zinv{p}*spdiags(sigmuvec,0,n,n) -X{p};
else
EinvRc{p} = sigmu*par.Zinv{p} -X{p};
end
Rq = sparse(n,n);
if (corrector) && (norm(par.parbarrier{p})==0)
Rq = Prod3(pblk,dX{p},dZ{p},par.Zinv{p},0);
Rq = 0.5*(Rq+Rq');
else
tmp = Prod3(pblk,X{p},Rd{p},par.Zinv{p},0,par.nzlistAy{p});
tmp = 0.5*(tmp+tmp');
tmp2 = AXfun(pblk,At(p,:),par.permA(p,:),{tmp});
hRd = hRd + tmp2;
end
EinvRc{p} = EinvRc{p} - Rq;
tmp2 = AXfun(pblk,At(p,:),par.permA(p,:),EinvRc(p));
hEinvRc = hEinvRc + tmp2;
elseif strcmp(pblk{1},'u')
rhsfree = [rhsfree; Rd{p}]; %#ok
end
end
%%
rhs = rp + hRd - hEinvRc;
rhs = full([rhs; rhsfree]);
%%*******************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
linsysolve.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/linsysolve.m
| 7,741 |
utf_8
|
2091e9d1c0858acfd5c4e07842ed787d
|
%%***************************************************************
%% linsysolve: solve linear system to get dy, and direction
%% corresponding to unrestricted variables.
%%
%% [xx,coeff,L,resnrm] = linsysolve(schur,UU,Afree,EE,rhs);
%%
%% child functions: symqmr.m, mybicgstable.m, linsysolvefun.m
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%***************************************************************
function [xx,coeff,L,resnrm] = linsysolve(par,schur,UU,Afree,EE,rhs)
global solve_ok exist_analytic_term
global nnzmat nnzmatold matfct_options matfct_options_old use_LU
global msg diagR diagRold numpertdiagschur
spdensity = par.spdensity;
printlevel = par.printlevel;
iter = par.iter;
if isfield(par,'relgap') && isfield(par,'pinfeas') && isfield(par,'dinfeas')
err = max([par.relgap,par.pinfeas,par.dinfeas]);
else
err = inf;
end
%%
m = length(schur);
if (iter==1);
use_LU = 0;
matfct_options_old = ''; %#ok
diagR = ones(m,1);
numpertdiagschur = 0;
end
if isempty(nnzmatold)
nnzmatold = 0; %#ok
end
diagRold = diagR;
%%
%% schur = schur + rho*diagschur + lam*AAt
%%
diagschur = abs(full(diag(schur)));
if (par.ublksize)
minrho(1) = 1e-15;
else
minrho(1) = 1e-17;
end
minrho(1) = max(minrho(1), 1e-6/3.0^iter); %% old: 1e-6/3.0^iter
minrho(2) = max(1e-04, 0.7^iter);
minlam = max(1e-10, 1e-4/2.0^iter);
rho = min(minrho(1), minrho(2)*(1+norm(rhs))/(1+norm(diagschur.*par.y)));
lam = min(minlam, 0.1*rho*norm(diagschur)/par.normAAt);
if (exist_analytic_term); rho = 0; end; %% important
ratio = max(diagR)/min(diagR);
if (par.depconstr) || (ratio > 1e10) || (iter < 5)
%% important: do not perturb beyond certain threshold
%% since it will adversely affect prim_infeas of fp43
%%
pertdiagschur = min(rho*diagschur,1e-4./max(1,abs(par.dy)));
mexschurfun(schur,full(pertdiagschur));
%%if (printlevel>2); fprintf(' %2.1e',rho); end
end
if (par.depconstr) || (par.ZpATynorm > 1e10) || (par.ublksize) || (iter < 10)
%% Note: do not add this perturbation even if ratio is large.
%% It adversely affects hinf15.
%%
lam = min(lam,1e-4/max(1,norm(par.AAt*par.dy)));
if (exist_analytic_term); lam = 0; end
mexschurfun(schur,lam*par.AAt);
%%if (printlevel>2); fprintf('*'); end
end
if (max(diagschur)/min(diagschur) > 1e14) && (par.blkdim(2) == 0) ...
&& (iter > 10)
tol = 1e-8;
idx = find(diagschur < tol); len = length(idx);
pertdiagschur = zeros(m,1);
if (len > 0 && len < 5) && (norm(rhs(idx)) < tol)
pertdiagschur(idx) = 1*ones(length(idx),1);
mexschurfun(schur,pertdiagschur);
numpertdiagschur = numpertdiagschur + 1;
if (printlevel>2); fprintf('#'); end
end
end
%%
%% assemble coefficient matrix
%%
len = size(Afree,2);
if ~isempty(EE)
EE(:,[1 2]) = len + EE(:,[1 2]); %% adjust for ublk
end
EE = [(1:len)' (1:len)' zeros(len,1); EE];
if isempty(EE)
coeff.mat22 = [];
else
coeff.mat22 = spconvert(EE);
end
if (size(Afree,2) || size(UU,2))
coeff.mat12 = [Afree, UU];
else
coeff.mat12 = [];
end
coeff.mat11 = schur; %% important to use perturbed schur matrix
ncolU = size(coeff.mat12,2);
%%
%% pad rhs with zero vector
%% decide which solution methods to use
%%
rhs = [rhs; zeros(m+ncolU-length(rhs),1)];
if (ncolU > 300); use_LU = 1; end
%%
%% Cholesky factorization
%%
L = []; resnrm = norm(rhs); xx = inf*ones(m,1);
if (~use_LU)
solve_ok = 1; solvesys = 1;
nnzmat = mexnnz(coeff.mat11);
% nnzmatdiff = (nnzmat ~= nnzmatold);
if (nnzmat > spdensity*m^2) || (m < 500)
matfct_options = 'chol';
else
matfct_options = 'spchol';
end
if (printlevel>2); fprintf(' %s ',matfct_options); end
L.matdim = length(schur);
if strcmp(matfct_options,'chol')
if issparse(schur); schur = full(schur); end;
if (iter<=5); %%--- to fix strange anonmaly in Matlab
mexschurfun(schur,1e-20,2);
end
L.matfct_options = 'chol';
[L.R,indef] = chol(schur);
L.perm = 1:m;
diagR = diag(L.R).^2;
elseif strcmp(matfct_options,'spchol')
if ~issparse(schur); schur = sparse(schur); end;
L.matfct_options = 'spchol';
[L.R,indef,L.perm] = chol(schur,'vector');
L.Rt = L.R';
diagR = full(diag(L.R)).^2;
end
if (indef)
diagR = diagRold;
solve_ok = -2; solvesys = 0;
msg = 'linsysolve: Schur complement matrix not positive definite';
if (printlevel); fprintf('\n %s',msg); end
end
if (solvesys)
if (ncolU)
tmp = coeff.mat12'*linsysolvefun(L,coeff.mat12)-coeff.mat22;
if issparse(tmp); tmp = full(tmp); end
tmp = 0.5*(tmp + tmp');
[L.Ml,L.Mu,L.Mp] = lu(tmp);
tol = 1e-16;
condest = max(abs(diag(L.Mu)))/min(abs(diag(L.Mu)));
if any(abs(diag(L.Mu)) < tol) || (condest > 1e30); %%old: 1e18
solvesys = 0; %#ok
solve_ok = -4; %#ok
use_LU = 1;
msg = 'SMW too ill-conditioned, switch to LU factor';
if (printlevel); fprintf('\n %s, %2.1e.',msg,condest); end
end
end
[xx,resnrm,solve_ok] = symqmr(coeff,rhs,L,[],[],printlevel);
if (solve_ok <= 0.3) && (printlevel)
fprintf('\n warning: symqmr failed: %3.1f ',solve_ok);
end
end
if (solve_ok <= 0.3)
tol = 1e-10;
if (m < 1e4 && strcmp(matfct_options,'chol') && (err > tol)) ...
|| (m < 2e5 && strcmp(matfct_options,'spchol') && (err > tol))
use_LU = 1;
if (printlevel); fprintf('\n switch to LU factor.'); end
end
end
end
%%
%% LU factorization
%%
if (use_LU)
nnzmat = mexnnz(coeff.mat11)+mexnnz(coeff.mat12);
% nnzmatdiff = (nnzmat ~= nnzmatold);
solve_ok = 1; solvesys = 1; %#ok
if ~isempty(coeff.mat22)
raugmat = [coeff.mat11, coeff.mat12; coeff.mat12', coeff.mat22];
else
raugmat = coeff.mat11;
end
if (nnzmat > spdensity*m^2) || (m+ncolU < 500)
matfct_options = 'lu'; %% lu is better than ldl
else
matfct_options = 'splu'; %% faster than spldl
end
if (printlevel>2); fprintf(' %s ',matfct_options); end
L.matdim = length(raugmat);
if strcmp(matfct_options,'lu')
if issparse(raugmat); raugmat = full(raugmat); end
L.matfct_options = 'lu';
[L.L,L.U,L.p] = lu(raugmat,'vector');
elseif strcmp(matfct_options,'splu')
if ~issparse(raugmat); raugmat = sparse(raugmat); end
L.matfct_options = 'splu';
[L.L,L.U,L.p,L.q,L.s] = lu(raugmat,'vector');
L.s = full(diag(L.s));
elseif strcmp(matfct_options,'ldl')
if issparse(raugmat); raugmat = full(raugmat); end
L.matfct_options = 'ldl';
[L.L,L.D,L.p] = ldl(raugmat,'vector');
L.D = sparse(L.D);
elseif strcmp(matfct_options,'spldl')
if ~issparse(raugmat); raugmat = sparse(raugmat); end
L.matfct_options = 'spldl';
[L.L,L.D,L.p,L.s] = ldl(raugmat,'vector');
L.s = full(diag(L.s));
L.Lt = L.L';
end
if (solvesys)
[xx,resnrm,solve_ok] = symqmr(coeff,rhs,L,[],[],printlevel);
%%[xx,resnrm,solve_ok] = mybicgstab(coeff,rhs,L,[],[],printlevel);
if (solve_ok<=0) && (printlevel)
fprintf('\n warning: bicgstab fails: %3.1f,',solve_ok);
end
end
end
if (printlevel>2); fprintf('%2.0d ',length(resnrm)-1); end
%%
nnzmatold = nnzmat; matfct_options_old = matfct_options;
%%***************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
schurmat_qblk.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/schurmat_qblk.m
| 3,205 |
utf_8
|
d154ddca57828c83c43efd37fbe64829
|
%%*******************************************************************
%% schurmat_qblk: compute schur matrix corresponding to SOCP blocks.
%%
%% HKM direction: output = schur + Ax*Ae' + Ae*Ax' - Ad*Ad'
%% NT direction: output = schur + Ae*Ae' - Ad*Ad'
%%
%% where schur = A*D*A', and Ad is the modification to ADA'
%% so that the latter is positive definite.
%%
%% [schur,UU,EE] = schurmat_qblk(blk,At,schur,UU,EE,p,dd,ee,xx);
%%
%% UU: stores the dense columns of Ax, Ae, Ad, and possibly
%% those of A*D^{1/2}. It has the form UU = [Ax Ae Ad].
%% EE: stores the assocaited (2,2) block matrix when the
%% output matrix is expressed as an augmented matrix.
%% It has the form EE = [0 -lam 0; -lam 0 0; 0 0 I].
%%
%% options = 0, HKM
%% = 1, NT
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%*******************************************************************
function [schur,UU,EE] = schurmat_qblk(blk,At,par,schur,UU,EE,p,dd,ee,xx)
global idxdenAq % nnzschur_qblk
if (nargin == 10); options = 0; else options = 1; end;
iter = par.iter;
if isempty(EE)
count = 0;
else
count = max(max(EE(:,2)),max(EE(:,1)));
end
pblk = blk(p,:); n = sum(pblk{2}); numblk = length(pblk{2});
%%
Ae = qprod(pblk,At{p}',ee{p});
if (options == 0)
Ax = qprod(pblk,At{p}',xx{p});
end
idxden = checkdense(Ae);
ddsch = dd{p};
if ~isempty(idxden);
spcolidx = setdiff(1:numblk,idxden);
s = 1 + [0, cumsum(pblk{2})];
idx = s(idxden);
tmp = zeros(n,1);
tmp(idx) = sqrt(2*abs(ddsch(idx)));
Ad = qprod(pblk,At{p}',tmp);
ddsch(idx) = abs(ddsch(idx));
if (options == 0)
len = length(idxden);
gamzsub = par.gamz{p}(idxden);
lam = gamzsub.*gamzsub;
UU = [UU, Ax(:,idxden), Ae(:,idxden)*spdiags(lam,0,len,len), Ad(:,idxden)];
tmp = (count+1:count+len)';
EE = [EE; [tmp, len+tmp, -lam; len+tmp, tmp, -lam; ...
2*len+tmp, 2*len+tmp, ones(len,1)] ];
count = count+3*len;
Ax = Ax(:,spcolidx); Ae = Ae(:,spcolidx);
tmp = Ax*Ae';
schur = schur + (tmp + tmp');
else
len = length(idxden);
w2 = par.gamz{p}./par.gamx{p};
lam = w2(idxden);
UU = [UU, Ae(:,idxden)*spdiags(sqrt(lam),0,len,len), Ad(:,idxden)];
tmp = (count+1:count+len)';
EE = [EE; [tmp, tmp, -lam; len+tmp, len+tmp, ones(len,1)] ];
count = count + 2*len;
Ae = Ae(:,spcolidx);
schur = schur + Ae*Ae';
end
else
if (options == 0)
tmp = Ax*Ae';
schur = schur + (tmp+tmp');
else
tmp = Ae*Ae';
schur = schur + tmp;
end
end
if (iter==1)
idxdenAq{p} = checkdense(At{p}');
end
if ~isempty(idxdenAq{p});
idxden = idxdenAq{p};
len = length(idxden);
Ad = At{p}(idxden,:)'*spdiags(sqrt(abs(ddsch(idxden))),0,len,len);
UU = [UU, Ad];
tmp = (count+1:count+len)';
EE = [EE; [tmp, tmp, -sign(ddsch(idxden))]];
% count = count + len;
ddsch(idxden) = zeros(len,1);
end
schurtmp = At{p}' *spdiags(ddsch,0,n,n) *At{p};
schur = schur + schurtmp;
%%*******************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
ops.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/ops.m
| 11,548 |
utf_8
|
0931c97ce9eb7f01a28fac581153ca1c
|
%%******************************************************************
%% ops:
%%
%% Z = ops(X,operand,Y,alpha);
%%
%% INPUT: X = a matrix or a scalar
%% or a CELL ARRAY consisting only of matrices
%% operand = sym, transpose, triu, tril,
%% real, imag, sqrt, abs, max, min, nnz,
%% spdiags, ones, zeros, norm, sum, row-norm, blk-norm
%% rank1, rank1inv, inv
%% +, -, *, .*, ./, .^
%% Y (optional) = a matrix or a scalar
%% or a CELL ARRAY consisting only of matrices
%% alpha (optional) = a scalar
%% or the variable blk.
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%******************************************************************
function Z = ops(X,operand,Y,alpha)
spdensity = 0.4;
if (nargin == 2)
if strcmp(operand,'sym');
if ~iscell(X);
[m,n] = size(X);
if (m == n);
Z = (X+X')/2;
elseif (n == 1);
Z = X;
else
error('X must be square matrix or a column vector');
end;
else
Z = cell(size(X));
for p = 1:length(X);
[m,n] = size(X{p});
if (m == n);
Z{p} = (X{p}+X{p}')/2;
elseif (n == 1);
Z{p} = X{p};
else
error('X{p} must be square matrix or a column vector');
end;
end;
end;
elseif strcmp(operand,'sqrt') || strcmp(operand,'abs') || ...
strcmp(operand,'real') || strcmp(operand,'imag');
if ~iscell(X);
eval(['Z = ',operand,'(X);']);
else
Z = cell(size(X));
for p = 1:length(X);
eval(['Z{p} = ',operand,'(X{p});']);
end;
end;
elseif strcmp(operand,'max') || strcmp(operand,'min') || ...
strcmp(operand,'sum');
if ~iscell(X);
eval(['Z = ',operand,'(X);']);
else
Z = [];
for p = 1:length(X);
eval(['Z = [Z ',operand,'(X{p})',' ];']);
end;
end;
eval(['Z = ',operand,'(Z);']);
elseif strcmp(operand,'transpose') || strcmp(operand,'triu') || ...
strcmp(operand,'tril');
if ~iscell(X);
if (size(X,1) == size(X,2));
Z = feval(operand,X);
elseif (size(X,2) == 1);
Z = X;
else
error('X must be square matrix or a column vector');
end;
else
Z = cell(size(X));
for p = 1:length(X);
if (size(X{p},1) == size(X{p},2));
Z{p} = feval(operand,X{p});
elseif (size(X{p},2) == 1);
Z{p} = X{p};
else
error('X{p} must be square matrix or a column vector');
end;
end;
end;
elseif strcmp(operand,'norm');
if ~iscell(X);
Z = full(sqrt(sum(sum(X.*X))));
else
Z = 0;
for p = 1:length(X); Z = Z + sum(sum(X{p}.*X{p})); end;
Z = sqrt(Z);
end;
elseif strcmp(operand,'blk-norm');
if ~iscell(X);
Z = full(sqrt(sum(sum(X.*X))));
else
Z = zeros(length(X),1);
for p = 1:length(X); Z(p) = sum(sum(X{p}.*X{p})); end;
Z = sqrt(Z);
end;
elseif strcmp(operand,'inv');
if ~iscell(X);
[m,n] = size(X); n2 = n*n;
if (m==n)
Z = inv(X);
if (nnz(Z) > spdensity*n2)
Z = full(Z);
else
Z = sparse(Z);
end
elseif (m > 1 && n == 1);
Z = 1./X;
if (nnz(Z) > spdensity*n)
Z = full(Z);
else
Z = sparse(Z);
end
end
else
Z = cell(size(X));
for p = 1:length(X);
[m,n] = size(X{p}); n2 = n*n;
if (m==n)
Z{p} = inv(X{p});
if (nnz(Z{p}) > spdensity*n2)
Z{p} = full(Z{p});
else
Z{p} = sparse(Z{p});
end
elseif (m > 1 && n == 1);
Z{p} = 1./X{p};
if (nnz(Z{p}) > spdensity*n)
Z{p} = full(Z{p});
else
Z{p} = sparse(Z{p});
end
end
end
end
elseif strcmp(operand,'getM');
if ~iscell(X);
Z = size(X,1);
else
for p = 1:length(X); Z(p) = size(X{p},1); end; %#ok
Z = sum(Z);
end;
elseif strcmp(operand,'nnz');
if ~iscell(X);
Z = nnz(X);
else
for p = 1:length(X);
Z(p) = nnz(X{p}); %#ok
end;
Z = sum(Z);
end;
elseif strcmp(operand,'ones');
if ~iscell(X);
Z = ones(size(X));
else
Z = cell(size(X));
for p = 1:length(X);
Z{p} = ones(size(X{p}));
end
end
elseif strcmp(operand,'zeros');
if ~iscell(X);
[m,n] = size(X);
Z = sparse(m,n);
else
Z = cell(size(X));
for p = 1:length(X);
[m,n] = size(X{p});
Z{p} = sparse(m,n);
end
end
elseif strcmp(operand,'identity');
blk = X;
Z = cell(size(blk,1),1);
for p = 1:size(blk,1)
pblk = blk(p,:); n = sum(pblk{2});
if strcmp(pblk{1},'s')
Z{p} = speye(n,n);
elseif strcmp(pblk{1},'q')
s = 1+[0, cumsum(pblk{2})];
len = length(pblk{2});
Z{p} = zeros(n,1);
Z{p}(s(1:len)) = ones(len,1);
elseif strcmp(pblk{1},'l')
Z{p} = ones(n,1);
elseif strcmp(pblk{1},'u')
Z{p} = zeros(n,1);
end
end
elseif strcmp(operand,'row-norm');
if ~iscell(X);
if (size(X,2) == size(X,1));
Z = sqrt(sum((X.*conj(X))'))'; %#ok
elseif (size(X,2) == 1);
Z = abs(X);
end
else
Z = cell(size(X));
for p = 1:length(X);
if (size(X{p},2) == size(X{p},1));
Z{p} = sqrt(sum((X{p}.*conj(X{p}))'))'; %#ok
elseif (size(X{p},2) == 1);
Z{p} = abs(X{p});
end
end
end
end
end
%%
if (nargin == 3)
if strcmp(operand,'spdiags');
if ~iscell(Y);
[m,n] = size(Y);
if (m == n);
Z = spdiags(X,0,m,n);
else
Z = X;
end
else
Z = cell(size(Y));
for p = 1:length(Y);
[m,n] = size(Y{p});
if (m == n);
Z{p} = spdiags(X{p},0,m,n);
else
Z{p} = X{p};
end
end
end
elseif strcmp(operand,'inprod')
if ~iscell(X) && ~iscell(Y)
Z = (Y'*X)';
elseif iscell(X) && iscell(Y)
Z = zeros(size(X{1},2),1);
for p=1:length(X)
Z = Z + (Y{p}'*X{p})';
end
end
elseif strcmp(operand,'+') || strcmp(operand,'-') || ...
strcmp(operand,'/') || strcmp(operand,'./') || ...
strcmp(operand,'*') || strcmp(operand,'.*') || ...
strcmp(operand,'.^');
if (~iscell(X) && ~iscell(Y));
eval(['Z = X',operand,'Y;']);
elseif (iscell(X) && iscell(Y))
Z = cell(size(X));
for p = 1:length(X);
if (size(X{p},2) == 1) && (size(Y{p},2) == 1) && ...
(strcmp(operand,'*') || strcmp(operand,'/'));
eval(['Z{p} = X{p}.',operand,'Y{p};']);
else
eval(['Z{p} = X{p} ',operand,'Y{p};']);
end
end
elseif (iscell(X) && ~iscell(Y));
if (length(Y) == 1); Y = Y*ones(length(X),1); end
Z = cell(size(X));
for p = 1:length(X);
eval(['Z{p} = X{p}',operand,'Y(p);']);
end
elseif (~iscell(X) && iscell(Y));
Z = cell(size(Y));
if (length(X) == 1); X = X*ones(length(Y),1); end
for p = 1:length(Y);
eval(['Z{p} = X(p)',operand,'Y{p};']);
end
end
else
error([operand,' is not available, check input arguments']);
end
end
%%
if (nargin == 4)
if strcmp(operand,'rank1') || strcmp(operand,'rank1inv');
Z = cell(size(alpha,1),1);
for p = 1:size(alpha,1);
if ~strcmp(alpha{p,1},'diag');
blktmp = alpha{p,2};
if (length(blktmp) == 1);
if strcmp(operand,'rank1');
Z{p} = (X{p}*Y{p}' + Y{p}*X{p}')/2;
else
Z{p} = 2./(X{p}*Y{p}' + Y{p}*X{p}');
end
else
Xp = X{p};
Yp = Y{p};
n = sum(blktmp);
Zp = sparse(n,n);
s = [0 cumsum(blktmp)];
if strcmp(operand,'rank1');
for i = 1:length(blktmp)
pos = s(i)+1 : s(i+1);
x = Xp(pos);
y = Yp(pos);
Zp(pos,pos) = sparse((x*y' + y*x')/2); %#ok
end;
Z{p} = Zp;
else
for i = 1:length(blktmp)
pos = s(i)+1 : s(i+1);
x = Xp(pos);
y = Yp(pos);
Zp(pos,pos) = sparse(2./(x*y' + y*x')); %#ok
end
Z{p} = Zp;
end
end
elseif strcmp(alpha{p,1},'diag');
if strcmp(operand,'rank1');
Z{p} = X{p}.*Y{p};
else
Z{p} = 1./(X{p}.*Y{p});
end
end
end
elseif strcmp(operand,'+') || strcmp(operand,'-');
if ~iscell(X) && ~iscell(Y);
eval(['Z = X',operand,'alpha*Y;']);
elseif (iscell(X) && iscell(Y));
Z = cell(size(X));
if (length(alpha) == 1);
alpha = alpha*ones(length(X),1);
end
if strcmp(operand,'+'),
for p = 1:length(X)
Z{p} = X{p} + alpha(p) * Y{p};
end
else
for p = 1:length(X);
Z{p} = X{p} - alpha(p) * Y{p};
end
end
else
error('X, Y are different objects');
end
else
error([operand,' is not available']);
end
end
%%============================================================
|
github
|
xiaoxiaojiangshang/Programs-master
|
schurmat_lblk.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/schurmat_lblk.m
| 1,010 |
utf_8
|
11b66919604e457c631f5ed67225fc45
|
%%*******************************************************************
%% schurmat_lblk: compute A*D*A'
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%*******************************************************************
function [schur,UU,EE] = schurmat_lblk(blk,At,par,schur,UU,EE,p,dd)
global idxdenAl
iter = par.iter;
n = sum(blk{p,2});
if (iter==1)
idxdenAl{p} = checkdense(At{p}');
end
ddsch = dd{p};
if ~isempty(idxdenAl{p});
idxden = idxdenAl{p};
len = length(idxden);
Ad = At{p}(idxden,:)' *spdiags(sqrt(ddsch(idxden)),0,len,len);
UU = [UU, Ad];
if isempty(EE)
count = 0;
else
count = max(max(EE(:,1)),max(EE(:,2)));
end
tmp = (count + 1: count+len)';
EE = [EE; [tmp, tmp, -ones(len,1)] ];
ddsch(idxden) = zeros(len,1);
end
schurtmp = At{p}' *spdiags(ddsch,0,n,n) *At{p};
schur = schur + schurtmp;
%%*******************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
sqlpmisc.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/sqlpmisc.m
| 4,078 |
utf_8
|
1dc032b6e1fd72eb26f2f3e519a746dd
|
%%*****************************************************************************
%% sqlpmisc:
%% unscale and produce infeasibility certificates if appropriate
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004.
%%*****************************************************************************
function [X,y,Z,termcode,resid,reldist,msg] = sqlpmisc(blk,At,C,b,X,y,Z,permZ,param)
termcode = param.termcode;
iter = param.iter;
obj = param.obj;
relgap = param.relgap;
prim_infeas = param.prim_infeas;
dual_infeas = param.dual_infeas;
homRd = param.homRd;
homrp = param.homrp;
AX = param.AX;
ZpATynorm = param.ZpATynorm;
m0 = param.m0;
indeprows = param.indeprows;
normX0 = param.normX0;
normZ0 = param.normZ0;
inftol = param.inftol;
maxit = param.maxit;
scale_data = param.scale_data;
printlevel = param.printlevel;
%%
resid = []; reldist = []; msg = [];
if (scale_data)
normA = param.normA; normC = param.normC; normb = param.normb;
else
normA = 1; normC = 1; normb = 1;
end
Anorm = ops(At,'norm'); xnorm = ops(X,'norm'); ynorm = norm(y);
infeas = max(prim_infeas,dual_infeas);
%%
if (iter >= maxit)
termcode = -6;
msg = 'sqlp stop: maximum number of iterations reached';
if (printlevel); fprintf('\n %s',msg); end
end
if (termcode <= 0)
%%
%% To detect near-infeasibility when the algorithm provides
%% a "better" certificate of infeasibility than of optimality.
%%
err = max(infeas,relgap);
iflag = 0;
if (obj(2) > 0)
if (homRd < 0.1*sqrt(err*inftol))
iflag = 1;
msg = sprintf('prim_inf,dual_inf,relgap = %3.2e, %3.2e, %3.2e',...
prim_infeas,dual_infeas,relgap);
if (printlevel); fprintf('\n %s',msg); end
termcode = 1;
end
end
if (obj(1) < 0)
if (homrp < 0.1*sqrt(err*inftol))
iflag = 1;
msg = sprintf('prim_inf,dual_inf,relgap = %3.2e, %3.2e, %3.2e',...
prim_infeas,dual_infeas,relgap);
if (printlevel); fprintf('\n %s',msg); end
termcode = 2;
end
end
if (iflag == 0)
if (scale_data == 1)
X = ops(ops(X,'./',normA),'*',normb);
y = y*normC;
Z = ops(ops(Z,'.*',normA),'*',normC);
end
end
end
if (termcode == 1) && (iter > 3)
msg = 'sqlp stop: primal problem is suspected of being infeasible';
if (printlevel); fprintf('\n %s',msg); end
if (scale_data == 1)
X = ops(X,'./',normA); b = b*normb;
end
rby = 1/(b'*y); y = rby*y; Z = ops(Z,'*',rby);
resid = ZpATynorm * rby;
reldist = ZpATynorm/(Anorm*ynorm);
end
if (termcode == 2) && (iter > 3)
msg = 'sqlp stop: dual problem is suspected of being infeasible';
if (printlevel); fprintf('\n %s',msg); end
if (scale_data == 1)
C = ops(C,'.*',normC);
Z = ops(Z,'.*',normA);
end
tCX = blktrace(blk,C,X);
X = ops(X,'*',1/(-tCX));
resid = norm(AX)/(-tCX);
reldist = norm(AX)/(Anorm*xnorm);
end
if (termcode == 3)
maxblowup = max(ops(X,'norm')/normX0,ops(Z,'norm')/normZ0);
msg = sprintf('sqlp stop: primal or dual is diverging, %3.1e',maxblowup);
if (printlevel); fprintf('\n %s',msg); end
end
[X,Z] = unperm(blk,permZ,X,Z);
if ~isempty(indeprows)
ytmp = zeros(m0,1);
ytmp(indeprows) = y;
y = ytmp;
end
%%*****************************************************************************
%% unperm: undo the permutations applied in validate.
%%
%% [X,Z] = unperm(blk,permZ,X,Z);
%%
%% undoes the permutation introduced in validate.
%%*****************************************************************************
function [X,Z] = unperm(blk,permZ,X,Z)
%%
for p = 1:size(blk,1)
if (strcmp(blk{p,1},'s') && ~isempty(permZ{p}))
per = permZ{p};
X{p} = X{p}(per,per);
Z{p} = Z{p}(per,per);
end
end
%%*****************************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
checkdense.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/checkdense.m
| 730 |
utf_8
|
6d44b41643ef16f78b42927e1fc03dd8
|
%%********************************************************************
%% checkdense : identify the dense columns of a matrix
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%********************************************************************
function idxden = checkdense(A)
[m,n] = size(A);
idxden = [];
nzratio = 1;
if (m > 1000); nzratio = 0.20; end;
if (m > 2000); nzratio = 0.10; end;
if (m > 5000); nzratio = 0.05; end;
if (nzratio < 1)
nzcolA = sum(spones(A));
idxden = find(nzcolA > nzratio*m);
if (length(idxden) > max(200,0.1*n))
idxden = [];
end
end
%%********************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
NTrhsfun.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/NTrhsfun.m
| 4,253 |
utf_8
|
51c74223afc232c456def8488b51aa3f
|
%%*******************************************************************
%% NTrhsfun: compute the right-hand side vector of the
%% Schur complement equation for the NT direction.
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%*******************************************************************
function [rhs,EinvRc,hRd] = NTrhsfun(blk,At,par,X,Z,rp,Rd,sigmu,hRd,dX,dZ)
spdensity = par.spdensity;
m = length(rp);
if (nargin > 8)
corrector = 1;
else
corrector = 0;
hRd = zeros(m,1);
end
hEinvRc = zeros(m,1);
EinvRc = cell(size(blk,1),1);
rhsfree = [];
%%
for p = 1:size(blk,1)
pblk = blk(p,:);
n = sum(pblk{2}); numblk = length(pblk{2});
if strcmp(pblk{1},'l')
if iscell(sigmu)
EinvRc{p} = sigmu{p}./Z{p} -X{p};
else
EinvRc{p} = sigmu./Z{p} -X{p};
end
Rq = sparse(n,1);
if (corrector) && (norm(par.parbarrier{p})==0)
Rq = dX{p}.*dZ{p}./Z{p};
else
tmp = par.dd{p}.*Rd{p};
tmp2 = mexMatvec(At{p},tmp,1);
hRd = hRd + tmp2;
end
EinvRc{p} = EinvRc{p} - Rq;
tmp2 = mexMatvec(At{p},EinvRc{p},1);
hEinvRc = hEinvRc + tmp2;
elseif strcmp(pblk{1},'q')
if iscell(sigmu)
EinvRc{p} = qops(pblk,-sigmu{p}./(par.gamz{p}.*par.gamz{p}),Z{p},4) -X{p};
else
EinvRc{p} = qops(pblk,-sigmu./(par.gamz{p}.*par.gamz{p}),Z{p},4) -X{p};
end
Rq = sparse(n,1);
if (corrector) && (norm(par.parbarrier{p})==0)
w = sqrt(par.gamz{p}./par.gamx{p});
hdx = qops(pblk,w,par.ff{p},5,dX{p});
hdz = qops(pblk,w,par.ff{p},6,dZ{p});
hdxdz = Arrow(pblk,hdx,hdz);
vv = qops(pblk,w,par.ff{p},5,X{p});
Vihdxdz = Arrow(pblk,vv,hdxdz,1);
Rq = qops(pblk,w,par.ff{p},6,Vihdxdz);
else
tmp = par.dd{p}.*Rd{p} + qops(pblk,qops(pblk,Rd{p},par.ee{p},1),par.ee{p},3);
tmp2 = mexMatvec(At{p},tmp,1);
hRd = hRd + tmp2;
end
EinvRc{p} = EinvRc{p} - Rq;
tmp2 = mexMatvec(At{p},EinvRc{p},1);
hEinvRc = hEinvRc + tmp2;
elseif strcmp(pblk{1},'s')
n2 = pblk{2}.*(pblk{2}+1)/2;
if iscell(sigmu)
%%ss = [0,cumsum(pblk{2})];
%%sigmuvec = zeros(n,1);
%%for k = 1:length(pblk{2});
%% sigmuvec(ss(k)+1:ss(k+1)) = sigmu{p}(k)*ones(pblk{2}(k),1);
%%end
sigmuvec = mexexpand(pblk{2},sigmu{p});
tmp = spdiags(sigmuvec./par.sv{p} -par.sv{p},0,n,n);
else
tmp = spdiags(sigmu./par.sv{p} -par.sv{p},0,n,n);
end
EinvRc{p} = Prod3(pblk,par.G{p}',tmp,par.G{p},1);
Rq = sparse(n,n);
if (corrector) && (norm(par.parbarrier{p})==0)
hdZ = Prod3(pblk,par.G{p},dZ{p},par.G{p}',1);
hdX = spdiags(qops(pblk,par.parbarrier{p}',1./par.sv{p},3)-par.sv{p},0,n,n)-hdZ;
tmp = Prod2(pblk,hdX,hdZ,0);
tmp = 0.5*(tmp+tmp');
if (numblk == 1)
d = par.sv{p};
e = ones(pblk{2},1);
Rq = 2*tmp./(d*e'+e*d');
if (nnz(Rq) <= spdensity*n2); Rq = sparse(Rq); end
else
Rq = sparse(n,n);
ss = [0, cumsum(pblk{2})];
for i = 1:numblk
pos = ss(i)+1 : ss(i+1);
d = par.sv{p}(pos); e = ones(length(pos),1);
Rq(pos,pos) = 2*tmp(pos,pos)./(d*e' + e*d'); %#ok
end
end
Rq = Prod3(pblk,par.G{p}',Rq,par.G{p},1);
else
tmp = Prod3(pblk,par.W{p},Rd{p},par.W{p},1,par.nzlistAy{p});
tmp2 = AXfun(pblk,At(p,:),par.permA(p,:),{tmp});
hRd = hRd + tmp2;
end
EinvRc{p} = EinvRc{p} - Rq;
tmp2 = AXfun(pblk,At(p,:),par.permA(p,:),EinvRc(p));
hEinvRc = hEinvRc + tmp2;
elseif strcmp(pblk{1},'u')
rhsfree = [rhsfree; Rd{p}]; %#ok
end
end
%%
rhs = rp + hRd - hEinvRc;
rhs = full([rhs; rhsfree]);
%%*******************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
SDPvalBounds.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/SDPvalBounds.m
| 1,843 |
utf_8
|
fa3af856805cc15685c38e69218a8ffb
|
%%*****************************************************************
%% compute lower and upper bounds for the exact primal
%% optimal value.
%%
%% LB <= true optimal dual value = true optimal primal value <= UB.
%%
%%*****************************************************************
function [LB,UB] = SDPvalBounds(blk,At,C,b,X,y,mu)
if (nargin < 7); mu = 1.1; end
Aty = Atyfun(blk,At,[],[],y);
Znew = ops(C,'-',Aty);
%%
eigX = cell(size(blk,1),1);
for p = 1:size(blk,1)
pblk = blk(p,:);
if strcmp(pblk{1},'s')
eigX{p} = eig(full(X{p}));
elseif strcmp(pblk{1},'l')
eigX{p} = X{p};
end
end
%%
%% compute lower bound
%%
pert = 0;
for p = 1:size(blk,1)
pblk = blk(p,:);
if strcmp(pblk{1},'s')
eigtmp = eig(full(Znew{p}));
idx = find(eigtmp < 0);
Xbar = mu*max(eigX{p});
elseif strcmp(pblk{1},'l')
eigtmp = Znew{p};
idx = find(eigtmp < 0);
Xbar = mu*max(eigX{p});
end
numneg = length(idx);
if (numneg)
%%mineig = min(eigtmp(idx));
pert = pert + Xbar*sum(eigtmp(idx));
%%fprintf('\n numneg = %3.0d, mineigZnew = %- 3.2e',numneg,mineig);
end
end
LB0 = b'*y;
LB = b'*y + pert;
fprintf('\n <b,y> = %-10.9e, LB = %-10.9e\n',LB0,LB);
%%
%% compute upper bound
%%
Xbar = X;
%% construct Xbar that is positive semidefinite
for p = 1:size(blk,1)
pblk = blk(p,:);
n = sum(pblk{2});
eigXp = eigX{p};
if strcmp(pblk{1},'s')
Xbar{p} = Xbar{p} - min(eigXp)*speye(n,n);
elseif strcmp(pblk{1},'l')
Xbar{p} = Xbar{p} - min(eigXp)*ones(n,1);
end
end
Rp = b-AXfun(blk,At,[],Xbar);
UB = blktrace(blk,C,Xbar) + mu*abs(y)'*abs(Rp);
UB0 = blktrace(blk,C,X);
fprintf('\n <C,X> = %-10.9e, UB = %-10.9e\n',UB0,UB);
%%*****************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
NTscaling.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/NTscaling.m
| 1,847 |
utf_8
|
82a266e8bf9cf33993f0bff10650c15c
|
%%**********************************************************************
%% NTscaling: Compute NT scaling matrix
%%
%% compute SVD of Xchol*Zchol via eigenvalue decompostion of
%% Zchol * X * Zchol' = V * diag(sv2) * V'.
%% compute W satisfying W*Z*W = X.
%% W = G'*G, where G = diag(sqrt(sv)) * (invZchol*V)'
%% important to keep W symmertic.
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%**********************************************************************
function [W,G,sv,gamx,gamz,dd,ee,ff] = ...
NTscaling(blk,X,Z,Zchol,invZchol)
numblk = size(blk,1);
W = cell(numblk,1); G = cell(numblk,1); sv = cell(numblk,1);
gamx = cell(numblk,1); gamz = cell(numblk,1);
dd = cell(numblk,1); ee = cell(numblk,1); ff = cell(numblk,1);
%%
for p = 1:size(blk,1)
pblk = blk(p,:);
n = sum(pblk{2});
if strcmp(pblk{1},'l')
dd{p} = X{p}./Z{p}; %% do not add perturbation, it badly affects cre-a
elseif strcmp(pblk{1},'q');
gamx{p} = sqrt(qops(pblk,X{p},X{p},2));
gamz{p} = sqrt(qops(pblk,Z{p},Z{p},2));
w2 = gamz{p}./gamx{p}; w = sqrt(w2);
dd{p} = qops(pblk,1./w2,ones(n,1),4);
tt = qops(pblk,1./w,Z{p},3) - qops(pblk,w,X{p},4);
gamtt = sqrt(qops(pblk,tt,tt,2));
ff{p} = qops(pblk,1./gamtt,tt,3);
ee{p} = qops(pblk,sqrt(2)./w,ff{p},4);
elseif strcmp(pblk{1},'s')
tmp = Prod2(pblk,Zchol{p},X{p},0);
tmp = Prod2(pblk,tmp,Zchol{p}',1);
[sv2,V] = blkeig(pblk,tmp);
sv2 = max(1e-20,sv2);
sv{p} = sqrt(sv2);
tmp = Prod2(pblk,invZchol{p},V);
G{p} = Prod2(pblk,spdiags(sqrt(sv{p}),0,n,n),tmp');
W{p} = Prod2(pblk,G{p}',G{p},1);
end
end
%%**********************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
linsysolvefun.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/linsysolvefun.m
| 1,276 |
utf_8
|
7ca4a2896ad33a210a95d53138f0676f
|
%%*************************************************************************
%% linsysolvefun: Solve H*x = b
%%
%% x = linsysolvefun(L,b)
%% where L contains the triangular factors of H.
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%*************************************************************************
function x = linsysolvefun(L,b)
x = zeros(size(b));
for k=1:size(b,2)
if strcmp(L.matfct_options,'chol')
x(L.perm,k) = mextriang(L.R, mextriang(L.R,b(L.perm,k),2) ,1);
%% x(L.perm,k) = L.R \ (b(L.perm,k)' / L.R)';
elseif strcmp(L.matfct_options,'spchol')
x(L.perm,k) = mextriangsp(L.Rt,mextriangsp(L.R,b(L.perm,k),2),1);
elseif strcmp(L.matfct_options,'ldl')
x(L.p,k) = ((L.D\ (L.L \ b(L.p,k)))' / L.L)';
elseif strcmp(L.matfct_options,'spldl')
btmp = b(:,k).*L.s;
xtmp(L.p,1) = L.Lt\ (L.D\ (L.L \ btmp(L.p))); %#ok
x(:,k) = xtmp.*L.s;
elseif strcmp(L.matfct_options,'lu')
x(:,k) = L.U \ (L.L \ b(L.p,k));
elseif strcmp(L.matfct_options,'splu')
btmp = b(:,k)./L.s;
x(L.q,k) = L.U \ (L.L \ (btmp(L.p)));
end
end
%%*************************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
sqlpdemo.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/sqlpdemo.m
| 6,011 |
utf_8
|
793deabad8688259781993ce346cea24
|
%%*****************************************************************
%% Examples of SQLP.
%%
%% this is an illustration on how to use our SQLP solvers
%% coded in sqlp.m
%%
%% feas = 1 if want feasible initial iterate
%% = 0 otherwise
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%*****************************************************************
function sqlpdemo
randn('seed',0); rand('seed',0); %#ok
feas = input('using feasible starting point? [yes = 1, no = 0] ');
if (feas)
fprintf('\n using feasible starting point\n\n');
else
fprintf('\n using infeasible starting point\n\n');
end
pause(1);
ntrials = 1;
% iterm = zeros(2,6); infom = zeros(2,6); timem = zeros(2,6);
sqlparameters;
for trials = 1:ntrials
for eg = 1:6
if (eg == 1);
disp('******** random sdp **********')
n = 10; m = 10;
[blk,At,C,b,X0,y0,Z0] = randsdp(n,[],[],m,feas);
text = 'random SDP';
elseif (eg == 2);
disp('******** Norm minimization problem. **********')
n = 10; m = 5; B = [];
for k = 1:m+1; B{k} = randn(n); end; %#ok
[blk,At,C,b,X0,y0,Z0] = norm_min(B,feas);
text = 'Norm min. pbm';
elseif (eg == 3);
disp('******** Max-cut *********');
N = 10;
B = graph(N);
[blk,At,C,b,X0,y0,Z0] = maxcut(B,feas);
text = 'Maxcut';
elseif (eg == 4);
disp('********* ETP ***********')
N = 10;
B = randn(N); B = B*B';
[blk,At,C,b,X0,y0,Z0] = etp(B,feas);
text = 'ETP';
elseif (eg == 5);
disp('**** Lovasz theta function ****')
N = 10;
B = graph(N);
[blk,At,C,b,X0,y0,Z0] = thetaproblem(B,feas);
text = 'Lovasz theta fn.';
elseif (eg == 6);
disp('**** Logarithmic Chebyshev approx. pbm. ****')
N = 20; m = 5;
B = rand(N,m); f = rand(N,1);
[blk,At,C,b,X0,y0,Z0] = logcheby(B,f,feas);
text = 'Log. Chebyshev approx. pbm';
end;
%%
% m = length(b);
nn = 0;
for p = 1:size(blk,1),
nn = nn + sum(blk{p,2});
end
%%
Gap = []; Feas = []; legendtext = {};
for vers = [1 2];
OPTIONS.vers = vers;
[obj,X,y,Z,infoall,runhist] = ...
sqlp(blk,At,C,b,OPTIONS,X0,y0,Z0); %#ok
gaphist = runhist.gap;
infeashist = max([runhist.pinfeas; runhist.dinfeas]);
Gap(vers,1:length(gaphist)) = gaphist; %#ok
Feas(vers,1:length(infeashist)) = infeashist; %#ok
if (vers==1); legendtext{end+1} = 'HKM'; %#ok
elseif (vers==2); legendtext{end+1} = 'NT'; %#ok
end;
end;
h = plotgap(Gap,Feas);
xlabel(text);
legend(h(h~=0),legendtext{:});
fprintf('\n**** press enter to continue ****\n'); pause
end
end
%%
%%======================================================================
%% plotgap: plot the convergence curve of
%% duality gap and infeasibility measure.
%%
%% h = plotgap(Gap,Feas);
%%
%% Input: Gap = each row of Gap corresponds to a convergence curve
%% of the duality gap for an SDP.
%% Feas = each row of Feas corresponds to a convergence curve
%% of the infeasibility measure for an SDP.
%%
%% Output: h = figure handle.
%%
%% SDPT3: version 3.0
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last modified: 7 Jul 99
%%********************************************************************
function h = plotgap(Gap,Feas)
clf;
set(0,'defaultaxesfontsize',12);
set(0,'defaultlinemarkersize',2);
set(0,'defaulttextfontsize',12);
%%
%% get axis scale for plotting duality gap
%%
tmp = [];
for k = 1:size(Gap,1);
g = Gap(k,:);
if ~isempty(g);
g = g(g > 5*eps);
tmp = [tmp abs(g)]; %#ok
iter(k) = length(g); %#ok
else
iter(k) = 0; %#ok
end
end;
ymax = exp(log(10)*(round(log10(max(tmp)))+0.5));
ymin = exp(log(10)*min(floor(log10(tmp)))-0.5);
xmax = 5*ceil(max(iter)/5);
%%
%% plot duality gap
%%
color = '-r --b--m-c ';
if nargin == 2; subplot('position',[0.05 0.3 0.45 0.45]); end;
for k = 1:size(Gap,1);
g = Gap(k,:);
if ~isempty(g);
idx = find(g > 5*eps);
if ~isempty(idx); g = g(idx); len = length(g);
semilogy(len-1,g(len),'.b','markersize',12); hold on;
h(k) = semilogy(idx-1,g,color([3*(k-1)+1:3*k]),'linewidth',2); %#ok
end;
end;
end;
title('duality gap'); axis('square');
if nargin == 1; axis([0 xmax ymin ymax]); end;
hold off;
%%
%% get axis scale for plotting infeasibility
%%
if nargin == 2;
tmp = [];
for k = 1:size(Feas,1);
f = Feas(k,:);
if ~isempty(f);
f = f(f>0);
tmp = [tmp abs(f)]; %#ok
iter(k) = length(f); %#ok
else
iter(k) = 0; %#ok
end
end;
fymax = exp(log(10)*(round(log10(max(tmp)))+0.5));
fymin = exp(log(10)*(min(floor(log10(tmp)))-0.5));
ymax = max(ymax,fymax); ymin = min(ymin,fymin);
xmax = 5*ceil(max(iter)/5);
axis([0 xmax ymin ymax]);
%%
%% plot infeasibility
%%
subplot('position',[0.5 0.3 0.45 0.45]);
for k = 1:size(Feas,1);
f = Feas(k,:);
f(1) = max(f(1),eps);
if ~isempty(f);
idx = find(f > 1e-20);
if ~isempty(idx); f = f(idx); len = length(f);
semilogy(len-1,f(len),'.b','markersize',12); hold on;
h(k) = semilogy(idx-1,f,color([3*(k-1)+1:3*k]),'linewidth',2); %#ok
end;
end;
end;
title('infeasibility measure');
axis('square'); axis([0 xmax ymin max(1,ymax)]);
hold off;
end;
%%====================================================================
|
github
|
xiaoxiaojiangshang/Programs-master
|
gpcomp.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/gpcomp.m
| 5,095 |
utf_8
|
7e23e98588f834156a9f13545f77cb3b
|
%%*********************************************************************
%% gpcomp: Compute tp=1/gp in Proposition 2 of the paper:
%%
%% R.M. Freund, F. Ordonez, and K.C. Toh,
%% Behavioral measures and their correlation with IPM iteration counts
%% on semi-definite programming problems,
%% Mathematical Programming, 109 (2007), pp. 445--475.
%%
%% [gp,info,Xfeas,blk2,At2,C2,b2] = gpcomp(blk,At,C,b,OPTIONS,solveyes);
%%
%% Xfeas = a feasible X for the primal problem if gp is finite.
%% That is,
%% norm(b-AXfun(blk,At,[],Xfeas))
%% should be small
%%*********************************************************************
function [gp,info,Xfeas,blk2,At2,C2,b2] = gpcomp(blk,At,C,b,OPTIONS,solveyes)
if (nargin < 6); solveyes = 1; end
if (nargin < 5)
OPTIONS = sqlparameters;
OPTIONS.vers = 1;
OPTIONS.gaptol = 1e-10;
OPTIONS.printlevel = 3;
end
if isempty(OPTIONS); OPTIONS = sqlparameters; end
if ~isfield(OPTIONS,'solver'); OPTIONS.solver = 'sqlp'; end
if ~isfield(OPTIONS,'printlevel'); OPTIONS.printlevel = 3; end
if ~iscell(C); tmp = C; clear C; C{1} = tmp; end
%%
%% convert ublk to lblk
%%
% exist_ublk = 0;
for p = 1:size(blk,1)
pblk = blk(p,:);
if strcmp(pblk{1},'u');
% exist_ublk = 1;
fprintf('\n converting ublk into the difference of two non-negative vectors');
blk{p,1} = 'l'; blk{p,2} = 2*sum(blk{p,2});
At{p} = [At{p}; -At{p}];
C{p} = [C{p}; -C{p}];
end
end
%%
m = length(b);
blk2 = blk;
At2 = At;
C2 = cell(size(blk,1),1);
b2 = zeros(m,1);
%%
%%
%%
dd = ones(1,m);
ee = zeros(1,m); EE = cell(size(blk,1),1);
% exist_ublk = 0;
nn = zeros(size(blk,1),1);
for p = 1:size(blk,1)
pblk = blk(p,:);
n = sum(pblk{2});
if strcmp(pblk{1},'s')
ee = ee + svec(pblk,speye(n),1)'*At{p};
C2{p,1} = sparse(n,n);
EE{p} = speye(n);
nn(p) = n;
elseif strcmp(pblk{1},'q')
eq = zeros(n,1);
idx1 = 1+[0,cumsum(pblk{2})];
idx1 = idx1(1:length(idx1)-1);
eq(idx1) = ones(length(idx1),1);
ee = ee + 2*eq'*At{p};
C2{p,1} = zeros(n,1);
EE{p} = eq;
nn(p) = length(pblk{2});
elseif strcmp(pblk{1},'l')
ee = ee + ones(1,n)*At{p};
C2{p,1} = zeros(n,1);
EE{p} = ones(n,1);
nn(p) = n;
elseif strcmp(pblk{1},'u')
C2{p,1} = zeros(n,1);
% exist_ublk = 1;
EE{p} = sparse(n,1);
nn(p) = n;
end
dd = dd + sqrt(sum(At{p}.*At{p}));
end
dd = 1./min(1e4,max(1,dd));
ee = ee.*dd;
b = b.*dd';
%%
%% scale data
%%
D = spdiags(dd',0,m,m);
for p = 1:size(blk,1)
% pblk = blk(p,:);
At2{p} = At2{p}*D;
end
%%
%% New variables in primal problem:
%% [x; tt; theta].
%%
numblk = size(blk,1);
blk2{numblk+1,1} = 'l'; blk2{numblk+1,2} = 2;
At2{numblk+1,1} = [ee; -b'];
C2{numblk+1,1} = [-1; 0];
%%
%% 3 additional inequality constraints in primal problem.
%%
ss = 0;
for p = 1:size(blk,1)
pblk = blk(p,:);
n = sum(pblk{2});
if strcmp(pblk{1},'s')
n2 = sum(pblk{2}.*(pblk{2}+1))/2;
At2{p} = [At2{p}, svec(pblk,speye(n,n),1), sparse(n2,2)];
ss = ss + n;
elseif strcmp(pblk{1},'q')
eq = zeros(n,1);
idx1 = 1+[0,cumsum(pblk{2})];
idx1 = idx1(1:length(idx1)-1);
eq(idx1) = ones(length(idx1),1);
At2{p} = [At2{p}, sparse(eq), sparse(n,2)];
ss = ss + 2*length(pblk{2});
elseif strcmp(pblk{1},'l')
At2{p} = [At2{p}, sparse(ones(n,1)), sparse(n,2)];
ss = ss + n;
elseif strcmp(pblk{1},'u')
At2{p} = [At2{p}, sparse(n,3)];
end
end
At2{numblk+1} = sparse([At2{numblk+1}, [ss;0], [0;1], [1;-1]]);
b2 = [b2; 1; 1; 0];
%%
%% Add in the linear block corresponding to the 3 slack variables.
%%
blk2{numblk+2,1} = 'l'; blk2{numblk+2,2} = 3;
At2{numblk+2,1} = [sparse(3,m), speye(3,3)];
C2{numblk+2,1} = zeros(3,1);
%%
%% Solve SDP
%%
gp = []; info = []; Xfeas = [];
if (solveyes)
if strcmp(OPTIONS.solver,'sqlp')
[X0,y0,Z0] = infeaspt(blk2,At2,C2,b2,2,100);
[obj,X,y,Z,info] = sqlp(blk2,At2,C2,b2,OPTIONS,X0,y0,Z0); %#ok
elseif strcmp(OPTIONS.solver,'HSDsqlp')
[obj,X,y,Z,info] = HSDsqlp(blk2,At2,C2,b2,OPTIONS); %#ok
else
[obj,X,y,Z,info] = sdpt3(blk2,At2,C2,b2,OPTIONS); %#ok
end
obj = -obj;
tt = X{numblk+1}(1); theta = X{numblk+1}(2);
Xfeas = ops(ops(X(1:numblk),'+',EE(1:numblk),tt),'/',theta);
%%
if (obj(1) > 0) || (abs(obj(1)) < 1e-8)
gp = 1/abs(obj(1));
elseif (obj(2) > 0)
gp = 1/obj(2);
else
gp = 1/exp(mean(log(abs(obj))));
end
err = max(info.dimacs([1,3,6]));
if (OPTIONS.printlevel)
fprintf('\n ******** gp = %3.2e, err = %3.1e\n',gp,err);
if (err > 1e-6);
fprintf('\n----------------------------------------------------')
fprintf('\n gp problem is not solved to sufficient accuracy');
fprintf('\n----------------------------------------------------\n')
end
end
end
%%*********************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
sqlparameters.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/sqlparameters.m
| 5,137 |
utf_8
|
76bbd09e284250f7770836baabcc95e5
|
%%*************************************************************************
%% parameters.m: set OPTIONS structure to specify default
%% parameters for sqlp.m
%%
%% OPTIONS.vers : version of direction to use.
%% 1 for HKM direction
%% 2 for NT direction
%% 0 for the default (which uses the HKM direction if
%% semidefinite blocks exist; and NT direction of SOCP problms)
%% OPTIONS.gam : step-length parameter,
%% OPTIONS.predcorr : whether to use Mehrotra predictor-corrector.
%% OPTIONS.expon : exponent in decrease of centering parameter sigma.
%% OPTIONS.gaptol : tolerance for duality gap as a fraction of the
%% value of the objective functions.
%% OPTIONS.inftol : tolerance for stopping due to suspicion of
%% infeasibility.
%% OPTIONS.steptol : toloerance for stopping due to small steps.
%% OPTIONS.maxit : maximum number of iteration allowed
%% OPTIONS.printlevel : 3, if want to display result in each iteration,
%% 2, if want to display only summary,
%% 1, if want to display warning message,
%% 0, no display at all.
%% OPTIONS.stoplevel : 2, if want to automatically detect termination;
%% 1, if want to automatically detect termination, but
%% restart automatically with a new iterate
%% when the algorithm stagnants because of tiny step-lengths.
%% 0, if want the algorithm to continue forever except for
%% successful completion, maximum number of iterations, or
%% numerical failures. Note, do not change this field unless
%% you very sure.
%% OPTIONS.scale_data : 1, if want to scale the data before solving the problem,
%% else = 0
%% OPTIONS.rmdepconstr : 1, if want to remove nearly dependent constraints,
%% else = 0.
%% OPTIONS.smallblkdim : block-size threshold determining what method to compute the
%% schur complement matrix corresponding to semidefintie block.
%% NOTE: this number should be small, say less than 20.
%% OPTIONS.parbarrier : parameter values of the log-barrier terms in the SQLP problem.
%% Default = [], meaning that the parameter values are all 0.
%% OPTIONS.schurfun : [], if no user supplied routine to compute the Schur matrix,
%% else, it is a cell array where each cell is either [],
%% or contains a string that is the file name where the Schur matrix
%% of the associated block data is computed.
%% For example, if the SQLP data has the block structure
%% blk{1,1} = '1'; blk{1,2} = 10;
%% blk{2,1} = 's'; blk{2,2} = 50;
%% and
%% OPTIONS.schurfun{1} = [];
%% OPTIONS.schurfun{2} = 'myownschur', where
%% 'myownschur' is a function with the calling sequence:
%% function schur = myownschur(X2,Z2inv,schurfun_par(2,:));
%% This means that for the first block, the Schur
%% matrix is computed by the default method in SDPT3,
%% and for the second block, the user supplies the
%% routine to compute the associated Schur matrix.
%% OPTIONS.schurfun_par: [], if no user supplied routine to compute the Schur matrix,
%% else, it is a cell array where the p-th row is either [],
%% or is a cell array containing the parameters needed in
%% the user supplied Schur routine OPTIONS.schurfun{p}.
%% For example, for the block structure described
%% above, we may have:
%% OPTIONS.schurfun_par{1} = [];
%% OPTIONS.schurfun_par{2,1} = par1;
%% OPTIONS.schurfun_par{2,2} = par2;
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%*************************************************************************
function OPTIONS = sqlparameters
OPTIONS.vers = 0;
OPTIONS.gam = 0;
OPTIONS.predcorr = 1;
OPTIONS.expon = 1;
OPTIONS.gaptol = 1e-8;
OPTIONS.inftol = 1e-8;
OPTIONS.steptol = 1e-6;
OPTIONS.maxit = 100;
OPTIONS.printlevel = 3;
OPTIONS.stoplevel = 1; %% do not change this field unless you very sure.
OPTIONS.scale_data = 0;
OPTIONS.spdensity = 0.4;
OPTIONS.rmdepconstr = 0;
OPTIONS.smallblkdim = 50;
OPTIONS.parbarrier = [];
OPTIONS.schurfun = [];
OPTIONS.schurfun_par = [];
%%*************************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
convertcmpsdp.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/convertcmpsdp.m
| 3,465 |
utf_8
|
6bd9a62cfb0249da5d75665cfb26063b
|
%%*********************************************************
%% convertcmpsdp: convert SDP with complex data into one
%% with real data by converting
%%
%% C - sum_{k=1}^m yk*Ak psd
%% to
%% [CR,-CI] - sum ykR*[AkR,-AkI] psd
%% [CI, CR] [AkI, AkR]
%%
%% ykI = 0 for k = 1:m
%%
%% [bblk,AAt,CC,bb] = convertcmpsdp(blk,A,C,b);
%%
%%*********************************************************
function [bblk,AAt,CC,bb,iscmp] = convertcmpsdp(blk,A,C,b)
m = length(b);
pp = size(A,1);
if (pp ~= size(blk,1))
error('blk and A not compatible');
end
numblk = size(blk,1);
iscmp = zeros(numblk,m+1);
for p = 1:size(blk,1)
len = size(A(p),2);
for k = 1:len
if ~isempty(A{p,k})
iscmp(p,k) = 1-isreal(A{p,k});
end
end
iscmp(p,m+1) = 1-isreal(C{p});
end
iscmp = norm(iscmp,'fro');
%%
if (iscmp == 0)
%% data is real
bblk = blk; AAt = A; CC = C; bb = b;
return;
end
%%
bb = real(b);
bblk = cell(size(blk,1),2);
for p = 1:size(blk,1)
pblk = blk(p,:);
if (size(pblk{2},1) > size(pblk{2},2))
pblk{2} = pblk{2}';
end
if strcmp(pblk{1},'s')
ss = [0,cumsum(pblk{2})];
ss2 = [0,cumsum(2*pblk{2})];
n = sum(pblk{2});
n2 = sum(pblk{2}.*(pblk{2}+1))/2;
AR = cell(1,m); Ctmp = sparse(2*n,2*n);
if (size(A{p},1)==n2 && size(A{p},2)==m);
Atype = 1;
elseif (size(A(p),1)==1 && size(A(p),2)==1);
Atype = 2;
else
error('convertcmp: At is not properly coded');
end
for k = 0:m
if (k == 0)
Ak = C{p};
else
if (Atype == 1)
Ak = smat(pblk,A{p}(:,k),1);
elseif (Atype == 2)
Ak = A{p,k};
end
end
Atmp = sparse(2*n,2*n);
if (length(pblk{2}) == 1)
tmp = [real(Ak),-imag(Ak); imag(Ak), real(Ak)];
if (k==0)
Ctmp = tmp;
else
Atmp = tmp;
end
else
for j = 1:length(pblk{2})
idx = ss(j)+1: ss(j+1);
Akj = Ak(idx,idx);
tmp = [real(Akj),-imag(Akj); imag(Akj), real(Akj)];
idx2 = ss2(j)+1: ss2(j+1);
if (k==0)
Ctmp(idx2,idx2) = tmp; %#ok
else
Atmp(idx2,idx2) = tmp; %#ok
end
end
end
if (k==0);
CC{p,1} = Ctmp; %#ok
else
AR{k} = Atmp;
end
end
bblk{p,1} = 's'; bblk{p,2} = 2*pblk{2};
AAt(p,1) = svec(bblk(p,:),AR); %#ok
elseif strcmp(pblk{1},'q');
error('SOCP block with complex data is currently not allowed');
elseif strcmp(pblk{1},'l');
if isreal(A{p}) && isreal(C{p})
bblk(p,:) = blk(p,:);
AAt{p,1} = A{p}; CC{p,1} = C{p}; %#ok
else
error('data for linear block must be real');
end
elseif strcmp(pblk{1},'u');
if isreal(A{p}) && isreal(C{p})
bblk(p,:) = blk(p,:);
AAt{p,1} = A{p}; CC{p,1} = C{p}; %#ok
else
error('data for unrestricted block must be real');
end
end
end
%%*********************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
sqlpsummary.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/sqlpsummary.m
| 4,047 |
utf_8
|
78361a4e3dfeaeb73a7102b08ad30733
|
%%*****************************************************************************
%% sqlpsummary: print summary
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%*****************************************************************************
function sqlpsummary(info,ttime,infeas_org,printlevel)
iter = info.iter;
obj = info.obj;
gap = info.gap;
relgap = info.relgap;
prim_infeas = info.pinfeas;
dual_infeas = info.dinfeas;
termcode = info.termcode;
reldist = info.reldist;
resid = info.resid;
dimacs = info.dimacs;
totaltime = info.cputime;
%%
preproctime = ttime.preproc; pcholtime = ttime.pchol; dcholtime = ttime.dchol;
predtime = ttime.pred; pstep_predtime = ttime.pred_pstep; dstep_predtime = ttime.pred_pstep;
corrtime = ttime.corr; pstep_corrtime = ttime.corr_pstep; dstep_corrtime = ttime.corr_dstep;
misctime = ttime.misc;
%%
if (printlevel >= 2)
fprintf('\n------------------------------------------------');
fprintf('-------------------\n');
fprintf(' number of iterations = %2.0f\n',iter);
end
if (termcode <= 0)
if (printlevel >=2)
fprintf(' primal objective value = %- 9.8e\n',obj(1));
fprintf(' dual objective value = %- 9.8e\n',obj(2));
fprintf(' gap := trace(XZ) = %3.2e\n',gap);
fprintf(' relative gap = %3.2e\n',relgap);
fprintf(' actual relative gap = %3.2e\n',-diff(obj)/(1+sum(abs(obj))));
if ~isempty(infeas_org)
fprintf(' rel. primal infeas (scaled problem) = %3.2e\n',prim_infeas);
fprintf(' rel. dual " " " = %3.2e\n',dual_infeas);
fprintf(' rel. primal infeas (unscaled problem) = %3.2e\n',infeas_org(1));
fprintf(' rel. dual " " " = %3.2e\n',infeas_org(2));
else
fprintf(' rel. primal infeas = %3.2e\n',prim_infeas);
fprintf(' rel. dual infeas = %3.2e\n',dual_infeas);
end
fprintf(' norm(X), norm(y), norm(Z) = %3.1e, %3.1e, %3.1e\n',...
info.normX,info.normy,info.normZ);
fprintf(' norm(A), norm(b), norm(C) = %3.1e, %3.1e, %3.1e\n',...
info.normA,info.normb,info.normC);
end
elseif (termcode == 1)
if (printlevel >=2)
fprintf(' residual of primal infeasibility \n')
fprintf(' certificate (y,Z) = %3.2e\n',resid);
fprintf(' reldist to infeas. <= %3.2e\n',reldist);
end
elseif (termcode == 2)
if (printlevel >=2)
fprintf(' residual of dual infeasibility \n')
fprintf(' certificate X = %3.2e\n',resid);
fprintf(' reldist to infeas. <= %3.2e\n',reldist);
end
end
if (printlevel >=2)
fprintf(' Total CPU time (secs) = %3.2f \n',totaltime);
fprintf(' CPU time per iteration = %3.2f \n',totaltime/iter);
fprintf(' termination code = %2.0f\n',termcode);
fprintf(' DIMACS: %.1e %.1e %.1e %.1e %.1e %.1e\n',dimacs);
fprintf('------------------------------------------------');
fprintf('-------------------\n');
if (printlevel > 3)
fprintf(' Percentage of CPU time spent in various parts \n');
fprintf('------------------------------------------------');
fprintf('-------------------\n');
fprintf(' preproc Xchol Zchol pred pred_steplen corr corr_steplen misc\n')
tt = [preproctime, pcholtime, dcholtime, predtime, pstep_predtime, dstep_predtime];
tt = [tt, corrtime, pstep_corrtime, dstep_corrtime, misctime];
tt = tt/sum(tt)*100;
fprintf(' %3.1f %3.1f %3.1f %3.1f %3.1f %3.1f ',...
tt(1),tt(2),tt(3),tt(4),tt(5),tt(6));
fprintf(' %3.1f %3.1f %3.1f %3.1f\n',tt(7),tt(8),tt(9),tt(10));
fprintf('------------------------------------------------');
fprintf('-------------------\n');
end
end
%%*****************************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
checkdepconstr.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/checkdepconstr.m
| 6,926 |
utf_8
|
186362786fef9d7d3328ab9e5a9e117c
|
%%*****************************************************************************
%% checkdepconst: compute AAt to determine if the
%% constraint matrices Ak are linearly independent.
%%
%% [At,b,y,idxB,neardepconstr,feasible,AAt] = checkdepconstr(blk,At,b,y,rmdepconstr);
%%
%% rmdepconstr = 1, if want to remove dependent columns in At
%% = 0, otherwise.
%%
%% idxB = indices of linearly independent columns of original At.
%% neardepconstr = 1 if there is nearly dependent columns in At
%% = 0, otherwise.
%% Note: the definition of "nearly dependent" is dependent on the
%% threshold used to determine the small diagonal elements in
%% the LDLt factorization of A*At.
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%*****************************************************************************
function [At,b,y,idxB,neardepconstr,feasible,AAt] = ...
checkdepconstr(blk,At,b,y,rmdepconstr)
global existlowrank printlevel
global nnzmatold
%%
%% compute AAt
%%
m = length(b);
AAt = sparse(m,m); numdencol = 0; UU = [];
for p = 1:size(blk,1)
pblk = blk(p,:);
if strcmp(pblk{1},'s');
m1 = size(At{p,1},2); m2 = m - m1;
if (m2 > 0)
if (m2 > 0.3*m); AAt = full(AAt); end
dd = At{p,3};
lenn = size(dd,1);
idxD = [0; find(diff(dd(:,1))); lenn];
ss = [0, cumsum(pblk{3})];
if (existlowrank)
AAt(1:m1,1:m1) = AAt(1:m1,1:m1) + At{p,1}'*At{p,1}; %#ok
for k = 1:m2
idx = ss(k)+1 : ss(k+1);
idx2 = idxD(k)+1: idxD(k+1);
ii = dd(idx2,2)-ss(k); %% undo cumulative indexing
jj = dd(idx2,3)-ss(k);
len = pblk{3}(k);
Dk = spconvert([ii,jj,dd(idx2,4); len,len,0]);
tmp = svec(pblk,At{p,2}(:,idx)*Dk*At{p,2}(:,idx)');
tmp2 = AAt(1:m1,m1+k) + (tmp'*At{p,1})';
AAt(1:m1,m1+k) = tmp2; %#ok
AAt(m1+k,1:m1) = tmp2'; %#ok
end
end
DD = spconvert([dd(:,2:4); sum(pblk{3}),sum(pblk{3}),0]);
VtVD = (At{p,2}'*At{p,2})*DD;
VtVD2 = VtVD'.*VtVD;
for k = 1:m2
idx0 = ss(k)+1 : ss(k+1);
%%tmp = VtVD(idx0,:)' .* VtVD(:,idx0);
tmp = VtVD2(:,idx0);
tmp = tmp*ones(length(idx0),1);
tmp3 = AAt(m1+1:m1+m2,m1+k) + mexqops(pblk{3},tmp,ones(length(tmp),1),1);
AAt(m1+1:m1+m2,m1+k) = tmp3; %#ok
end
else
AAt = AAt + abs(At{p,1})'*abs(At{p,1});
end
else
decolidx = checkdense(At{p,1}');
if ~isempty(decolidx);
n2 = size(At{p,1},1);
dd = ones(n2,1);
len= length(decolidx);
dd(decolidx) = zeros(len,1);
AAt = AAt + (abs(At{p,1})' *spdiags(dd,0,n2,n2)) *abs(At{p,1});
tmp = At{p,1}(decolidx,:)';
UU = [UU, tmp]; %#ok
numdencol = numdencol + len;
else
AAt = AAt + abs(At{p,1})'*abs(At{p,1});
end
end
end
if (numdencol > 0) && (printlevel)
fprintf('\n number of dense column in A = %d',numdencol);
end
numdencol = size(UU,2);
%%
%%
%%
feasible = 1; neardepconstr = 0;
if ~issparse(AAt); AAt = sparse(AAt); end
nnzmatold = mexnnz(AAt);
rho = 1e-15;
diagAAt = diag(AAt);
mexschurfun(AAt,rho*max(diagAAt,1));
[L.R,indef,L.perm] = chol(AAt,'vector');
L.d = full(diag(L.R)).^2;
if (indef)
msg = 'AAt is not pos. def.';
idxB = 1:m;
neardepconstr = 1;
if (printlevel); fprintf('\n checkdepconstr: %s',msg); end
return;
end
%%
%% find independent rows of A
%%
dd = zeros(m,1);
idxB = (1:m)';
dd(L.perm) = abs(L.d);
idxN = find(dd < 1e-13*mean(L.d));
ddB = dd(setdiff(1:m,idxN));
ddN = dd(idxN);
if ~isempty(ddN) && ~isempty(ddB) && (min(ddB)/max(ddN) < 10)
%% no clear separation of elements in dd
%% do not label constraints as dependent
idxN = [];
end
if ~isempty(idxN)
neardepconstr = 1;
if (printlevel)
fprintf('\n number of nearly dependent constraints = %1.0d',length(idxN));
end
if (numdencol==0)
if (rmdepconstr)
idxB = setdiff((1:m)',idxN);
if (printlevel)
fprintf('\n checkdepconstr: removing dependent constraints...');
end
[W,resnorm] = findcoeffsub(blk,At,idxB,idxN);
tol = 1e-8;
if (resnorm > sqrt(tol))
idxB = (1:m)';
neardepconstr = 0;
if (printlevel)
fprintf('\n checkdepconstr: basis rows cannot be reliably identified,');
fprintf(' abort removing nearly dependent constraints');
end
return;
end
tmp = W'*b(idxB) - b(idxN);
nnorm = norm(tmp)/max(1,norm(b));
if (nnorm > tol)
feasible = 0;
if (printlevel)
fprintf('\n checkdepconstr: inconsistent constraints exist,');
fprintf(' problem is infeasible.');
end
else
feasible = 1;
for p = 1:size(blk,1)
At{p,1} = At{p,1}(:,idxB);
end
b = b(idxB);
y = y(idxB);
AAt = AAt(idxB,idxB);
end
else
if (printlevel)
fprintf('\n To remove these constraints,');
fprintf(' re-run sqlp.m with OPTIONS.rmdepconstr = 1.');
end
end
else
if (printlevel)
fprintf('\n warning: the sparse part of AAt may be nearly singular.');
end
end
end
%%*****************************************************************************
%% findcoeffsub:
%%
%% [W,resnorm] = findcoeffsub(blk,At,idXB,idXN);
%%
%% idXB = indices of independent columns of At.
%% idxN = indices of dependent columns of At.
%%
%% AB = At(:,idxB); AN = At(:,idxN) = AB*W
%%
%% SDPT3: version 3.0
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last modified: 2 Feb 01
%%*****************************************************************************
function [W,resnorm] = findcoeffsub(blk,At,idxB,idxN)
AB = []; AN = [];
for p = 1:size(blk,1)
AB = [AB; At{p,1}(:,idxB)]; %#ok
AN = [AN; At{p,1}(:,idxN)]; %#ok
end
n = size(AB,2);
%%
%%-----------------------------------------
%% find W so that AN = AB*W
%%-----------------------------------------
%%
[L,U,P,Q] = lu(sparse(AB));
rhs = P*AN;
Lhat = L(1:n,:);
W = Q*( U \ (Lhat \ rhs(1:n,:)));
resnorm = norm(AN-AB*W,'fro')/max(1,norm(AN,'fro'));
%%*****************************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
convertRcone.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/convertRcone.m
| 948 |
utf_8
|
afa3b210699dbf796a257cb53e92ef0d
|
%%***************************************************************
%% convertRcone: convert rotated cone to socp cone
%%
%% [blk,At,C,b,T] = convertRcone(blk,At,C,b);
%%
%%***************************************************************
function [blk,At,C,b,T] = convertRcone(blk,At,C,b)
T = cell(size(blk,1),1);
for p = 1:size(blk,1)
pblk = blk(p,:);
if strcmp(pblk{1},'r')
if (min(pblk{2}) < 3)
error('rotated cones must be at least 3-dimensional');
end
n = sum(pblk{2}); len = length(pblk{2});
ss = [0,cumsum(pblk{2})];
idx = 1+ss(1:len)';
ir2 = 1/sqrt(2)*ones(len,1);
dd = [idx,idx,ir2-1; idx,idx+1,ir2;
idx+1,idx,ir2; idx+1,idx+1,-ir2-1];
T{p} = speye(n,n) + spconvert([dd; n,n,0]);
blk{p,1} = 'q';
At{p,1} = T{p}*At{p,1};
C{p,1} = T{p}*C{p,1};
end
end
%%***************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
qops.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/qops.m
| 1,421 |
utf_8
|
bddd4e93643ef0eb5b6868ef41d2bec7
|
%%********************************************************
%% qops: Fu = qops(pblk,w,f,options,u);
%%
%% options = 1, Fu(i) = <wi,fi>
%% = 2, Fu(i) = 2*wi(1)*fi(1)-<wi,fi>
%% = 3, Fui = w(i)*fi
%% = 4, Fui = w(i)*fi, Fui(1) = -Fui(1).
%% options = 5, Fu = w [ f'*u ; ub + fb*alp ], where
%% alp = (f'*u + u0)/(1+f0);
%% options = 6, compute Finv*u.
%%
%% Note F = w [f0 fb'; fb I+ fb*fb'/(1+f0) ], where
%% f0*f0 - fb*fb' = 1.
%% Finv = (1/w) [f0 -fb'; -fb I+ fb*fb'/(1+f0) ].
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%********************************************************
function Fu = qops(pblk,w,f,options,u)
if (options >= 1 && options <= 4)
Fu = mexqops(pblk{2},w,f,options);
elseif (options == 5)
s = 1 + [0 cumsum(pblk{2})];
idx1 = s(1:length(pblk{2}));
inprod = mexqops(pblk{2},f,u,1);
tmp = (u(idx1)+inprod)./(1+f(idx1));
Fu = u + mexqops(pblk{2},tmp,f,3);
Fu(idx1) = inprod;
Fu = mexqops(pblk{2},w,Fu,3);
elseif (options == 6)
s = 1 + [0 cumsum(pblk{2})];
idx1 = s(1:length(pblk{2}));
gamprod = mexqops(pblk{2},f,u,2);
tmp = (u(idx1)+gamprod)./(1+f(idx1));
Fu = u - mexqops(pblk{2},tmp,f,3);
Fu(idx1) = gamprod;
Fu = mexqops(pblk{2},1./w,Fu,3);
end
%%********************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
HKMdirfun.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/HKMdirfun.m
| 1,703 |
utf_8
|
2e90b8de8daed6f5a9a6894232dbff6a
|
%%*******************************************************************
%% HKMdirfun: compute (dX,dZ), given dy, for the HKM direction.
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%*******************************************************************
function [dX,dy,dZ] = HKMdirfun(blk,At,par,Rd,EinvRc,X,xx,m)
global solve_ok
dX = cell(size(blk,1),1); dZ = cell(size(blk,1),1); dy = [];
if (any(isnan(xx)) || any(isinf(xx)))
solve_ok = 0;
fprintf('\n linsysolve: solution contains NaN or inf');
return;
end
%%
dy = xx(1:m);
count = m;
%%
for p=1:size(blk,1)
pblk = blk(p,:);
if strcmp(pblk{1},'l')
%%dZ{p} = Rd{p} - At{p}*dy;
dZ(p) = ops(Rd(p),'-',Atyfun(pblk,At(p,:),[],[],dy));
dX{p} = EinvRc{p} - par.dd{p}.*dZ{p};
elseif strcmp(pblk{1},'q')
%%dZ{p} = Rd{p} - At{p}*dy;
dZ(p) = ops(Rd(p),'-',Atyfun(pblk,At(p,:),[],[],dy));
tmp = par.dd{p}.*dZ{p} ...
+ qops(pblk,qops(pblk,dZ{p},par.Zinv{p},1),X{p},3) ...
+ qops(pblk,qops(pblk,dZ{p},X{p},1),par.Zinv{p},3);
dX{p} = EinvRc{p} - tmp;
elseif strcmp(pblk{1},'s')
%%dZ{p} = Rd{p} -smat(pblk,At{p}*dy(par.permA(p,:)),par.isspAy(p));
dZ(p) = ops(Rd(p),'-',Atyfun(pblk,At(p,:),par.permA(p,:),par.isspAy(p),dy));
tmp = Prod3(pblk,X{p},dZ{p},par.Zinv{p},0);
tmp = 0.5*(tmp+tmp');
dX{p} = EinvRc{p}-tmp;
elseif strcmp(pblk{1},'u');
n = sum(pblk{2});
dZ{p} = zeros(n,1);
dX{p} = xx(count+1:count+n);
count = count + n;
end
end
%%*******************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
symqmr.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/symqmr.m
| 3,957 |
utf_8
|
bf28cb72305cb0378a7b572d42f39ff6
|
%%*************************************************************************
%% symqmr: symmetric QMR with left (symmetric) preconditioner.
%% The preconditioner used is based on the analytical
%% expression of inv(A).
%%
%% [x,resnrm,solve_ok] = symqmr(A,b,L,tol,maxit)
%%
%% child function: linsysolvefun.m
%%
%% A = [mat11 mat12; mat12' mat22].
%% b = rhs vector.
%% if matfct_options = 'chol' or 'spchol'
%% L = Cholesky factorization of (1,1) block.
%% M = Cholesky factorization of
%% Schur complement of A ( = mat12'*inv(mat11)*mat12-mat22).
%% else
%% L = triangular factors of A.
%% M = not relevant.
%% end
%% resnrm = norm of qmr-generated residual vector b-Ax.
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%*************************************************************************
function [xx,resnrm,solve_ok] = symqmr(A,b,L,tol,maxit,printlevel)
N = length(b);
if (nargin < 6); printlevel = 1; end
if (nargin < 5) || isempty(maxit); maxit = max(30,length(A.mat22)); end;
if (nargin < 4) || isempty(tol); tol = 1e-10; end;
tolb = min(1e-4,tol*norm(b));
solve_ok = 1;
x = zeros(N,1);
if (norm(x))
if isstruct(A); Aq = matvec(A,x); else Aq=A*x; end;
r = b-Aq;
else
r = b;
end
err = norm(r); resnrm(1) = err; minres = err; xx = x;
if (err < 1e-3*tolb); return; end
q = precond(A,L,r);
tau_old = norm(q);
rho_old = r'*q;
theta_old = 0;
d = zeros(N,1);
res = r; Ad = zeros(N,1);
%%
%% main loop
%%
tiny = 1e-30;
for iter = 1:maxit
if isstruct(A); Aq = matvec(A,q); else Aq=A*q; end;
sigma = q'*Aq;
if (abs(sigma) < tiny)
solve_ok = 2;
if (printlevel); fprintf('*'); end;
break;
else
alpha = rho_old/sigma;
r = r - alpha*Aq;
end
u = precond(A,L,r);
theta = norm(u)/tau_old; c = 1/sqrt(1+theta^2);
tau = tau_old*theta*c;
gam = (c^2*theta_old^2); eta = (c^2*alpha);
d = gam*d + eta*q;
x = x + d;
%%
Ad = gam*Ad + eta*Aq;
res = res - Ad;
err = norm(res); resnrm(iter+1) = err; %#ok
if (err < minres); xx = x; minres = err; end
if (err < tolb); break; end
if (iter > 10)
if (err > 0.98*mean(resnrm(iter-10:iter)))
solve_ok = 0.5; break;
end
end
%%
if (abs(rho_old) < tiny)
solve_ok = 2;
if (printlevel); fprintf('*'); end;
break;
else
rho = r'*u;
beta = rho/rho_old;
q = u + beta*q;
end
rho_old = rho;
tau_old = tau;
theta_old = theta;
end
if (iter == maxit); solve_ok = 0.3; end;
%%
%%*************************************************************************
%% precond:
%%*************************************************************************
function Mx = precond(A,L,x)
m = L.matdim; m2 = length(x)-m;
Mx = zeros(length(x),1);
for iter = 1:1
if norm(Mx); r = full(x - matvec(A,Mx)); else r = full(x); end
r1 = r(1:m);
if (m2 > 0)
r2 = r(m+1:m+m2);
w = linsysolvefun(L,r1);
z = mexMatvec(A.mat12,w,1) - r2;
z = L.Mu \ (L.Ml \ (L.Mp*z));
r1 = r1 - mexMatvec(A.mat12,z);
end
d = linsysolvefun(L,r1);
if (m2 > 0)
d = [d; z]; %#ok
end
Mx = Mx + d;
end
%%*************************************************************************
%% matvec: matrix-vector multiply.
%% matrix = [A.mat11, A.mat12; A.mat12', A.mat22]
%%*************************************************************************
function Ax = matvec(A,x)
m = length(A.mat11); m2 = length(x)-m;
if issparse(x); x = full(x); end
if (m2 > 0)
x1 = x(1:m);
else
x1 = x;
end
Ax = mexMatvec(A.mat11,x1);
if (m2 > 0)
x2 = x(m+1:m+m2);
Ax = Ax + mexMatvec(A.mat12,x2);
Ax2 = mexMatvec(A.mat12,x1,1) + mexMatvec(A.mat22,x2);
Ax = [full(Ax); full(Ax2)];
end
%%*************************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
validate_startpoint.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/validate_startpoint.m
| 3,067 |
utf_8
|
572146bf8639c3d5066b6a790bca3ba8
|
%%***********************************************************************
%% validate_startpoint: validate_startpoint starting point X0,y0,Z0
%%
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%***********************************************************************
function [X0,Z0] = validate_startpoint(blk,X0,Z0,spdensity,iscmp)
if (nargin < 5); iscmp = 0; end
if (nargin < 4); spdensity = 0.4; end
%%
if ~iscell(X0) || ~iscell(Z0);
error('validate_startpoint: X0, Z0 must be cell arrays');
end
if (min(size(X0))~=1 || min(size(Z0))~=1);
error('validate_startpoint: cell array X, Z can only have 1 column or row');
end
if (size(X0,2) > size(X0,1)); X0 = X0'; end;
if (size(Z0,2) > size(Z0,1)); Z0 = Z0'; end;
for p = 1:size(blk,1)
pblk = blk(p,:);
n = sum(pblk{2});
n2 = sum(pblk{2}.*pblk{2});
numblk = length(pblk{2});
if strcmp(pblk{1},'s');
if (iscmp)
X0{p} = [real(X0{p}),-imag(X0{p}); imag(X0{p}), real(X0{p})];
Z0{p} = [real(Z0{p}),-imag(Z0{p}); imag(Z0{p}), real(Z0{p})];
end
if ~all(size(X0{p}) == n) || ~all(size(Z0{p}) == n);
error('validate_startpoint: blk and X0,Z0 are not compatible');
end
if (norm([X0{p}-X0{p}' Z0{p}-Z0{p}'],inf) > 2e-13);
error('validate_startpoint: X0,Z0 not symmetric');
end
if (nnz(X0{p}) < spdensity*n2) || (numblk > 1) ;
if ~issparse(X0{p}); X0{p} = sparse(X0{p}); end;
else
if issparse(X0{p}); X0{p} = full(X0{p}); end;
end
if (nnz(Z0{p}) < spdensity*n2) || (numblk > 1);
if ~issparse(Z0{p}); Z0{p} = sparse(Z0{p}); end;
else
if issparse(Z0{p}); Z0{p} = full(Z0{p}); end;
end
elseif strcmp(pblk{1},'q') || strcmp(pblk{1},'l') || strcmp(pblk{1},'u');
if ~all([size(X0{p},2) size(Z0{p},2)]==1);
error(['validate_startpoint: ',num2str(p),...
'-th block of X0,Z0 must be column vectors']);
end
if ~all([size(X0{p},1) size(Z0{p},1)]==n);
error('validate_startpoint: blk, and X0,Z0, are not compatible');
end
if (nnz(X0{p}) < spdensity*n);
if ~issparse(X0{p}); X0{p} = sparse(X0{p}); end;
else
if issparse(X0{p}); X0{p} = full(X0{p}); end;
end
if (nnz(Z0{p}) < spdensity*n);
if ~issparse(Z0{p}); Z0{p} = sparse(Z0{p}); end;
else
if issparse(Z0{p}); Z0{p} = full(Z0{p}); end;
end
if strcmp(pblk{1},'l') && (any(X0{p} < 1e-12) || any(Z0{p} < 1e-12))
error('X0 or Z0 is not in nonnegative cone');
end
if strcmp(pblk{1},'q');
s = 1+[0, cumsum(pblk{2})]; len = length(pblk{2});
if any(X0{p}(s(1:len)) < 1e-12) || any(Z0{p}(s(1:len)) < 1e-12)
error('X0 or Z0 is not in socp cone');
end
end
end
end
%%***********************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
Atyfun.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/Atyfun.m
| 1,471 |
utf_8
|
5af173811d5528ab49ca2a48bd4748ce
|
%%*********************************************************
%% Atyfun: compute sum_{k=1}^m yk*Ak.
%%
%% Q = Atyfun(blk,At,permA,isspAy,y);
%%
%% Note: permA and isspAy may be set to [].
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%**********************************************************
function Q = Atyfun(blk,At,permA,isspAy,y)
if isempty(permA); ismtpermA = 1; else ismtpermA = 0; end
Q = cell(size(blk,1),1);
if isempty(isspAy); isspAy = ones(size(blk,1),1); end
for p = 1:size(blk,1)
pblk = blk(p,:);
if strcmp(pblk{1},'s')
n = sum(pblk{2});
m1 = size(At{p,1},2);
if (~isempty(At{p,1}))
if (ismtpermA)
tmp = At{p,1}*y(1:m1);
else
tmp = At{p,1}*y(permA(p,1:m1),1);
end
Q{p} = smat(pblk,tmp,isspAy(p));
else
Q{p} = sparse(n,n);
end
if (length(pblk) > 2) %% for low rank constraints
len = sum(pblk{3});
m2 = length(pblk{3});
y2 = y(m1+1:m1+m2);
dd = At{p,3};
idxD = [0; find(diff(dd(:,1))); size(dd,1)];
yy2 = mexexpand(diff(idxD),y2);
DD = spconvert([dd(:,2:3),dd(:,4).*yy2; len,len,0]);
Q{p} = Q{p} + At{p,2}*DD*At{p,2}';
end
else
Q{p} = At{p,1}*y;
end
end
%%*********************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
blkcholfun.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/blkcholfun.m
| 1,247 |
utf_8
|
6d78842d748fad818d79a003e1238916
|
%%******************************************************************
%% blkcholfun: compute Cholesky factorization of X.
%%
%% [Xchol,indef] = blkcholfun(blk,X,permX);
%%
%% X = Xchol'*Xchol;
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%******************************************************************
function [Xchol,indef] = blkcholfun(blk,X,permX)
if (nargin == 2); permX = []; end;
if ~iscell(X);
indef = 0;
if strcmp(blk{1},'s');
if isempty(permX) || ~issparse(X);
[Xchol,indef] = chol(X);
else
[tmp,indef] = chol(X(permX,permX));
Xchol(:,permX) = tmp;
end
elseif strcmp(blk{1},'q')
gamx = qops(blk,X,X,2);
if any(gamx <= 0)
indef = 1;
end
Xchol = [];
elseif strcmp(blk{1},'l');
if any(X <= 0)
indef = 1;
end
Xchol = [];
elseif strcmp(blk{1},'u')
Xchol = [];
end
else
Xchol = cell(size(X));
for p = 1:size(blk,1)
[Xchol{p},indef(p)] = blkcholfun(blk(p,:),X{p}); %#ok
end
indef = max(indef);
end
%%=================================================================
|
github
|
xiaoxiaojiangshang/Programs-master
|
smat.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/smat.m
| 880 |
utf_8
|
184f4081013cebeae6150a22b224ebf9
|
%%*********************************************************
%% smat: compute the matrix smat(x).
%%
%% M = smat(blk,x,isspM);
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%**********************************************************
function M = smat(blk,xvec,isspM)
if (nargin < 3); isspM = zeros(size(blk,1),1); end
%%
if ~iscell(xvec)
if strcmp(blk{1},'s')
M = mexsmat(blk,xvec,isspM);
else
M = xvec;
end
else
M = cell(size(blk,1),1);
if (length(isspM)==1)
isspM = isspM*ones(size(blk,1),1);
end
for p=1:size(blk,1)
pblk = blk(p,:);
if strcmp(pblk{1},'s');
M{p} = mexsmat(pblk,xvec{p},isspM(p));
else
M{p} = xvec{p};
end
end
end
%%*********************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
sqlpcheckconvg.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/sqlpcheckconvg.m
| 8,298 |
utf_8
|
6acb41aefb05d5a53dbd501dabab2b33
|
%%*****************************************************************************
%% sqlpcheckconvg: check convergence.
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%*****************************************************************************
function [param,breakyes,restart,msg] = sqlpcheckconvg(param,runhist)
termcode = param.termcode;
iter = param.iter;
obj = param.obj;
relgap = param.relgap;
gap = param.gap;
prim_infeas = param.prim_infeas;
dual_infeas = param.dual_infeas;
mu = param.mu;
% homrp = param.homrp;
% homRd = param.homRd;
prim_infeas_bad = param.prim_infeas_bad;
dual_infeas_bad = param.dual_infeas_bad;
if (iter > 15)
prim_infeas_min = min(param.prim_infeas_min, max(prim_infeas,1e-10));
dual_infeas_min = min(param.dual_infeas_min, max(dual_infeas,1e-10));
else
prim_infeas_min = inf;
dual_infeas_min = inf;
end
printlevel = param.printlevel;
stoplevel = param.stoplevel;
ublksize = param.ublksize;
use_LU = param.use_LU;
numpertdiagschur = param.numpertdiagschur;
infeas = max(prim_infeas,dual_infeas);
restart = 0;
breakyes = 0;
msg = [];
%%
if (param.normX > 1e15*param.normX0 || param.normZ > 1e15*param.normZ0)
termcode = 3;
breakyes = 1;
end
err = max(infeas,relgap);
idx = max(2,iter-9): iter+1;
pratio = (1-runhist.pinfeas(idx)./runhist.pinfeas(idx-1))./runhist.pstep(idx);
dratio = (1-runhist.dinfeas(idx)./runhist.dinfeas(idx-1))./runhist.dstep(idx);
if (param.homRd < 0.1*sqrt(err*max(param.inftol,1e-13))) ...
&& (iter > 30 || termcode==3) && (mean(abs(dratio-1)) > 0.5)
termcode = 1;
breakyes = 1;
end
if (param.homrp < 0.1*sqrt(err*max(param.inftol,1e-13))) ...
&& (iter > 30 || termcode==3) && (mean(abs(pratio-1)) > 0.5)
termcode = 2;
breakyes = 1;
end
if (stoplevel) && (iter > 2) && (~breakyes)
prim_infeas_bad = ...
+ (prim_infeas > max(1e-10,1e2*prim_infeas_min) && (prim_infeas_min < 1e-2)) ...
+ (prim_infeas > prod(1.5-runhist.step(iter+1:iter-1))*runhist.pinfeas(iter-2));
dual_infeas_bad = ...
+ (dual_infeas > max(1e-8,1e3*dual_infeas_min) && (dual_infeas_min < 1e-2));
if (mu < 1e-8) || (use_LU)
idx = max(1,iter-1): iter;
elseif (mu < 1e-4);
idx = max(1,iter-2): iter;
else
idx = max(1,iter-3): iter;
end
gap_progress_bad = (infeas < 1e-4) && (relgap < 5e-3) ...
&& (gap > 0.9*exp(mean(log(runhist.gap(idx)))));
gap_progress_bad2 = (infeas < 1e-4) && (relgap < 1) ...
&& (gap > 0.95*exp(mean(log(runhist.gap(idx)))));
gap_ratio = runhist.gap(idx+1)./runhist.gap(idx);
idxtmp = max(1,iter-4): iter;
gap_ratio_tmp = runhist.gap(idxtmp+1)./runhist.gap(idxtmp);
gap_slowrate = min(0.8,max(0.6,2*mean(gap_ratio_tmp)));
idx2 = max(1,iter-10): iter;
gap_ratio2 = runhist.gap(idx2+1)./runhist.gap(idx2);
gap_slow = all(gap_ratio > gap_slowrate);
gap_slow2 = all(gap_ratio2 > gap_slowrate);
if (iter > 20) && (infeas < 1e-4 || prim_infeas_bad) ...
&& (max(infeas,relgap) < 1) ...
&& ~(min(runhist.step(idx)) > 0.2 && ublksize)
if (gap_slow && prim_infeas_bad && (relgap < 1e-3)) ...
|| (gap_slow2 && prim_infeas_bad && ublksize && (runhist.step(iter+1) > 0.2))
msg = 'stop: progress is too slow';
if (printlevel); fprintf('\n %s',msg); end
termcode = -5;
breakyes = 1;
elseif (max(infeas,relgap) < 1e-2) && (prim_infeas_bad)
if (relgap < max(0.2*prim_infeas,1e-2*dual_infeas))
msg = 'stop: relative gap < infeasibility';
if (printlevel); fprintf('\n %s',msg); end
termcode = -1;
breakyes = 1;
end
end
end
if (iter > 20) && (gap_progress_bad) ...
&& (prim_infeas_bad || any(runhist.step(idx) > 0.5))
msg = 'stop: progress is bad';
if (printlevel); fprintf('\n %s',msg); end
termcode = -5;
breakyes = 1;
end
if (iter > 20) && (gap_progress_bad2) ...
&& (numpertdiagschur > 10);
msg = 'stop: progress is bad';
if (printlevel); fprintf('\n %s',msg); end
termcode = -5;
breakyes = 1;
end
if (iter > 30) && (prim_infeas_bad) && (gap_slow) && (relgap < 1e-3) ...
&& (dual_infeas < 1e-5) && ~(min(runhist.step(idx)) > 0.2 && ublksize)
msg = 'stop: progress is bad*';
if (printlevel); fprintf('\n %s',msg); end
termcode = -5;
breakyes = 1;
end
if (iter > 30) && (dual_infeas_bad) && (relgap < 1e-3) ...
&& (dual_infeas < 1e-5) ...
&& ~(min(runhist.step(idx)) > 0.2 && ublksize) %#ok
msg = 'stop: dual infeas has deteriorated too much';
if (printlevel); fprintf('\n %s',msg); end
termcode = -5;
breakyes = 1;
end
if (iter > 50) && (prim_infeas/runhist.pinfeas(1) < 1e-6) ...
&& (dual_infeas/runhist.dinfeas(1) > 1e-3) ...
&& (runhist.step(iter+1) > 0.2) && (relgap > 1e-3)
msg = 'stop: lack of progress in dual infeas';
if (printlevel); fprintf('\n %s, homrp=%2.1e',msg,param.homrp); end
termcode = -5;
breakyes = 1;
end
if (iter > 50) && (dual_infeas/runhist.dinfeas(1) < 1e-6) ...
&& (prim_infeas/runhist.pinfeas(1) > 1e-3) ...
&& (runhist.step(iter+1) > 0.2) && (relgap > 1e-3)
msg = 'stop: lack of progress in primal infeas';
if (printlevel); fprintf('\n %s, homRd=%2.1e',msg,param.homRd); end
termcode = -5;
breakyes = 1;
end
if (min(runhist.infeas) < 1e-4 || (prim_infeas_bad && iter > 10)) ...
&& (max(runhist.infeas) > 1e-5) || (iter > 20)
relgap2 = abs(diff(obj))/(1+sum(abs(obj)));
if (relgap2 < 1e-3);
step_short = all(runhist.step(iter:iter+1) < 0.05) ;
elseif (relgap2 < 1) || (use_LU)
idx = max(1,iter-3): iter+1;
step_short = all(runhist.step(idx) < 0.03);
else
step_short = 0;
end
if (step_short) && (relgap2 < 1e-2)
msg = 'stop: steps too short consecutively';
if (printlevel); fprintf('\n %s',msg); end
termcode = -5;
breakyes = 1;
end
end
if (iter > 3 && iter < 20) && (infeas > 1) ...
&& (min(param.homrp,param.homRd) > min(1e-8,param.inftol)) ...
&& (max(runhist.step(max(1,iter-3):iter+1)) < 1e-3)
if (stoplevel == 2)
msg = 'stop: steps too short consecutively*';
if (printlevel)
fprintf('\n *** Too many tiny steps, advisable to restart');
fprintf(' with the following iterate.')
fprintf('\n *** Suggestion: [X0,y0,Z0] = infeaspt(blk,At,C,b,2,1e5);');
fprintf('\n %s',msg);
end
termcode = -5;
breakyes = 1;
elseif (stoplevel == 3)
msg = 'stop: steps too short consecutively*';
if (printlevel)
fprintf('\n *** Too many tiny steps even')
fprintf(' after restarting');
fprintf('\n %s',msg);
end
termcode = -5;
breakyes = 1;
else
if (printlevel)
fprintf('\n *** Too many tiny steps:')
fprintf(' restarting with the following iterate.')
fprintf('\n *** [X,y,Z] = infeaspt(blk,At,C,b,2,1e5);');
end
prim_infeas_min = 1e20;
prim_infeas_bad = 0;
restart = 1;
end
end
end
if (max(relgap,infeas) < param.gaptol)
msg = sprintf('stop: max(relative gap, infeasibilities) < %3.2e',param.gaptol);
if (printlevel); fprintf('\n %s',msg); end
termcode = 0;
breakyes = 1;
end
%%
param.prim_infeas_bad = prim_infeas_bad;
param.prim_infeas_min = prim_infeas_min;
param.dual_infeas_bad = dual_infeas_bad;
param.dual_infeas_min = dual_infeas_min;
param.termcode = termcode;
%%**************************************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
SDPT3soln_SEDUMIsoln.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/SDPT3soln_SEDUMIsoln.m
| 2,743 |
utf_8
|
1f7236a38116d782e7084afc40e90a10
|
%%**********************************************************
%% SDPT3soln_SEDUMIsoln: convert SQLP solution in SDPT3 format to
%% SeDuMi format
%%
%% [xx,yy,zz] = SDPT3soln_SEDUMIsoln(blk,X,y,Z,perm);
%%
%% usage: load SEDUMI_data_file (containing say, A,b,c,K)
%% [blk,At,C,b,perm] = read_sedumi(A,b,c,K);
%% [obj,X,y,Z] = sdpt3(blk,At,C,b);
%% [xx,yy,zz] = SDPT3soln_SEDUMIsoln(blk,X,y,Z,perm);
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%**********************************************************
function [xx,yy,zz] = SDPT3soln_SEDUMIsoln(blk,X,y,Z,perm)
yy = y;
xx = []; zz = [];
%%
%% extract unrestricted blk
%%
for p = 1:size(blk,1)
pblk = blk(p,:);
if strcmp(pblk{1},'u')
xx = [xx; X{p,1}]; %#ok
zz = [zz; Z{p,1}]; %#ok
end
end
%%
%% extract linear blk
%%
for p = 1:size(blk,1)
pblk = blk(p,:);
if strcmp(pblk{1},'l')
xx = [xx; X{p,1}]; %#ok
zz = [zz; Z{p,1}]; %#ok
end
end
%%
%% extract second order cone blk
%%
for p = 1:size(blk,1)
pblk = blk(p,:);
if strcmp(pblk{1},'q')
xx = [xx; X{p,1}]; %#ok
zz = [zz; Z{p,1}]; %#ok
end
end
%%
%% extract rotated cone blk
%%
for p = 1:size(blk,1)
pblk = blk(p,:);
if strcmp(pblk{1},'r')
xx = [xx; X{p,1}]; %#ok
zz = [zz; Z{p,1}]; %#ok
end
end
%%
%% extract semidefinite cone blk
%%
per = [];
len = 0;
for p = 1:size(blk,1)
pblk = blk(p,:);
if strcmp(pblk{1},'s')
sblk(p) = length(pblk{2}); %#ok
per = [per, perm{p}]; %#ok
len = len + sum(pblk{2}.*pblk{2});
end
end
sblk = sum(sblk);
cnt = 1;
Xsblk = cell(sblk,1); Zsblk = cell(sblk,1);
for p = 1:size(blk,1)
pblk = blk(p,:);
if strcmp(pblk{1},'s')
ss = [0,cumsum(pblk{2})];
numblk = length(pblk{2});
Xp = X{p,1};
Zp = Z{p,1};
for tt = 1:numblk
if (numblk > 1)
idx = ss(tt)+1: ss(tt+1);
Xsblk{cnt} = full(Xp(idx,idx));
Zsblk{cnt} = full(Zp(idx,idx));
else
Xsblk{cnt} = Xp;
Zsblk{cnt} = Zp;
end
cnt = cnt + 1;
end
end
end
if ~isempty(per)
Xsblk(per) = Xsblk; Zsblk(per) = Zsblk;
xtmp = zeros(len,1); ztmp = zeros(len,1);
cnt = 0;
for p = 1:sblk
if strcmp(pblk{1},'s')
idx = 1:length(Xsblk{p})^2;
xtmp(cnt+idx) = Xsblk{p}(:);
ztmp(cnt+idx) = Zsblk{p}(:);
cnt = cnt + length(idx);
end
end
xx = [xx; xtmp];
zz = [zz; ztmp];
end
%%**********************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
detect_ublk.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/detect_ublk.m
| 2,815 |
utf_8
|
819f087d73a97e1717b952ca2f3a407d
|
%%*******************************************************************
%% detect_ublk: search for implied free variables in linear
%% block.
%% [blk2,At2,C2,ublkinfo] = detect_ublk(blk,At,C);
%%
%% i1,i2: indices corresponding to splitting of unrestricted varaibles
%% i3 : remaining indices in the linear block
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%*******************************************************************
function [blk2,At2,C2,ublkinfo,parbarrier2,X2,Z2] = ...
detect_ublk(blk,At,C,parbarrier,X,Z,printlevel)
if (nargin < 7); printlevel = 1; end
blk2 = blk; At2 = At; C2 = C;
if (nargin >= 6)
parbarrier2 = parbarrier;
X2 = X; Z2 = Z;
else
X2 = []; Z2 = [];
end
numblk = size(blk,1);
ublkinfo = cell(size(blk,1),3);
tol = 1e-14;
%%
numblknew = numblk;
%%
for p = 1:numblk
pblk = blk(p,:);
m = size(At{p},2);
if strcmp(pblk{1},'l')
r = randmat(1,m,0,'n');
% stime = cputime;
Ap = At{p}'; Cp = C{p};
ApTr = (r*Ap)';
[sApTr,perm] = sort(abs(ApTr));
idx0 = find(abs(diff(sApTr)) < tol);
if ~isempty(idx0)
n = pblk{2};
i1 = perm(idx0); i2 = perm(idx0+1);
Api1 = Ap(:,i1);
Api2 = Ap(:,i2);
Cpi1 = Cp(i1)';
Cpi2 = Cp(i2)';
idxzr = abs(Cpi1+Cpi2) < tol & sum(abs(Api1+Api2),1) < tol;
if any(idxzr)
i1 = i1(idxzr');
i2 = i2(idxzr');
blk2{p,1} = 'u';
blk2{p,2} = length(i1);
At2{p} = Ap(:,i1)';
C2{p} = Cp(i1);
if (printlevel)
fprintf('\n %1.0d linear variables from unrestricted variable.\n',...
2*length(i1));
end
if (nargin >= 6)
parbarrier2{p} = parbarrier{p}(i1);
X2{p} = X{p}(i1)-X{p}(i2);
Z2{p} = zeros(length(i1),1);
end
i3 = setdiff(1:n,union(i1,i2));
if ~isempty(i3)
numblknew = numblknew + 1;
blk2{numblknew,1} = 'l';
blk2{numblknew,2} = length(i3);
At2{numblknew,1} = Ap(:,i3)';
C2{numblknew,1} = Cp(i3);
if (nargin >= 6)
parbarrier2{numblknew,1} = parbarrier{p}(i3);
X2{numblknew,1} = X{p}(i3); Z2{numblknew,1} = Z{p}(i3);
end
end
ublkinfo{p,1} = i1; ublkinfo{p,2} = i2; ublkinfo{p,3} = i3;
end
end
end
end
%%*******************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
combine_blk.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/combine_blk.m
| 2,358 |
utf_8
|
205279faec8f7b11c04bc75707a6eb77
|
%%*******************************************************************
%% combine_blk: combine small SDP blocks together,
%% combine all SOCP blocks together, etc
%%
%% [blk2,At2,C2,blkinfo] = combine_blk(blk,At,C);
%%
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%*******************************************************************
function [blk2,At2,C2,blkinfo] = combine_blk(blk,At,C)
blkinfo = zeros(size(blk,1),1);
for p = 1:size(blk,1)
pblk = blk(p,:);
if strcmp(pblk{1},'s')
if (sum(pblk{2}) < 100)
blkinfo(p) = 1;
end
elseif strcmp(pblk{1},'q')
blkinfo(p) = 2;
elseif strcmp(pblk{1},'r')
blkinfo(p) = 3;
elseif strcmp(pblk{1},'l')
blkinfo(p) = 4;
elseif strcmp(pblk{1},'u')
blkinfo(p) = 5;
end
end
numblk0 = length(find(blkinfo == 0));
numblk = numblk0 + length(union(blkinfo(blkinfo > 0),[]));
blk2 = cell(numblk,2); At2 = cell(numblk,1); C2 = cell(numblk,1);
cnt = 0;
idx = find(blkinfo==0); %% larger SDP blocks
if ~isempty(idx)
len = length(idx);
blk2(1:len,:) = blk(idx,:);
At2(1:len) = At(idx); C2(1:len) = C(idx);
cnt = len;
end
idx = find(blkinfo==1); %% smaller SDP blocks
Ctmp = []; idxstart = 0;
if ~isempty(idx)
cnt = cnt + 1;
blk2{cnt,1} = 's'; blk2{cnt,2} = [];
len = length(idx);
for k = 1:len
blk2{cnt,2} = [blk2{cnt,2}, blk{idx(k),2}];
At2{cnt} = [At2{cnt}; At{idx(k)}];
[ii,jj,vv] = find(C{idx(k)});
Ctmp = [Ctmp; [idxstart+ii,idxstart+jj,vv]]; %#ok
idxstart = idxstart + sum(blk{idx(k),2});
end
end
n = sum(blk2{cnt,2});
C2{cnt} = spconvert([Ctmp; n,n,0]);
%%
for L = 2:5
idx = find(blkinfo==L);
if ~isempty(idx)
cnt = cnt + 1;
if (L==2)
blk2{cnt,1} = 'q';
elseif (L==3)
blk2{cnt,1} = 'r';
elseif (L==4)
blk2{cnt,1} = 'l';
elseif (L==5)
blk2{cnt,1} = 'u';
end
blk2{cnt,2} = [];
len = length(idx);
for k = 1:len
blk2{cnt,2} = [blk2{cnt,2}, blk{idx(k),2}];
At2{cnt} = [At2{cnt}; At{idx(k)}];
C2{cnt} = [C2{cnt}; C{idx(k)}];
end
end
end
%%*******************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
Prod2.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/Prod2.m
| 1,882 |
utf_8
|
b291dcf07608872ed75bd82e48ff0b54
|
%%*******************************************************************
%% Prod2: compute the block diagonal matrix A*B
%%
%% C = Prod2(blk,A,B,options);
%%
%% INPUT: blk = a cell array describing the block structure of A and B
%% A,B = square matrices or column vectors.
%%
%% options = 0 if no special structure
%% 1 if C is symmetric
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%*******************************************************************
function C = Prod2(blk,A,B,options)
global spdensity
if (nargin == 3); options = 0; end;
iscellA = iscell(A); iscellB = iscell(B);
%%
if (~iscellA && ~iscellB)
if (size(blk,1) > 1);
error('Prod2: blk and A,B are not compatible');
end;
if strcmp(blk{1},'s')
numblk = length(blk{2});
isspA = issparse(A); isspB = issparse(B);
if (numblk > 1)
if ~isspA; A=sparse(A); isspA=1; end
if ~isspB; B=sparse(B); isspB=1; end
end
%%use_matlab = (options==0 && ~isspA && ~isspB) || (isspA && isspB);
use_matlab = (~isspA && ~isspB) || (isspA && isspB);
if (use_matlab)
C = A*B;
if (options==1); C = 0.5*(C+C'); end;
else
C = mexProd2(blk,A,B,options);
end
checksparse = (numblk==1) && (isspA || isspB);
if (checksparse)
n2 = sum(blk{2}.*blk{2});
if (mexnnz(C) <= spdensity*n2);
if ~issparse(C); C = sparse(C); end;
else
if issparse(C); C = full(C); end;
end
end
elseif (strcmp(blk{1},'q') || strcmp(blk{1},'l') || strcmp(blk{1},'u'))
C = A.*B;
end
else
error('Prod2: A,B must be matrices');
end
%%*******************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
NTdirfun.m
|
.m
|
Programs-master/matlab/cvx/sdpt3/Solver/NTdirfun.m
| 1,614 |
utf_8
|
a236e4d45e59db8824375b14ed6090a1
|
%%*******************************************************************
%% NTdirfun: compute (dX,dZ), given dy, for the NT direction.
%%
%% SDPT3: version 3.1
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last Modified: 16 Sep 2004
%%*******************************************************************
function [dX,dy,dZ] = NTdirfun(blk,At,par,Rd,EinvRc,xx,m)
global solve_ok
dX = cell(size(blk,1),1); dZ = cell(size(blk,1),1); dy = [];
if (any(isnan(xx)) || any(isinf(xx)))
solve_ok = 0;
fprintf('\n linsysolve: solution contains NaN or inf.');
return;
end
%%
dy = xx(1:m);
count = m;
%%
for p=1:size(blk,1)
pblk = blk(p,:);
if strcmp(pblk{1},'l')
%%dZ{p} = Rd{p} - At{p}*dy;
dZ(p) = ops(Rd(p),'-',Atyfun(pblk,At(p,:),[],[],dy));
tmp = par.dd{p}.*dZ{p};
dX{p} = EinvRc{p} - tmp;
elseif strcmp(pblk{1},'q')
%%dZ{p} = Rd{p} - At{p}*dy;
dZ(p) = ops(Rd(p),'-',Atyfun(pblk,At(p,:),[],[],dy));
tmp = par.dd{p}.*dZ{p} + qops(pblk,qops(pblk,dZ{p},par.ee{p},1),par.ee{p},3);
dX{p} = EinvRc{p} - tmp;
elseif strcmp(pblk{1},'s')
%%dZ{p} = Rd{p} - smat(pblk,At{p}*dy(par.permA(p,:)),par.isspAy(p));
dZ(p) = ops(Rd(p),'-',Atyfun(pblk,At(p,:),par.permA(p,:),par.isspAy(p),dy));
tmp = Prod3(pblk,par.W{p},dZ{p},par.W{p},1);
dX{p} = EinvRc{p}-tmp;
elseif strcmp(pblk{1},'u');
n = sum(pblk{2});
dZ{p} = zeros(n,1);
dX{p} = xx(count+1:count+n);
count = count + n;
end
end
%%*******************************************************************
|
github
|
xiaoxiaojiangshang/Programs-master
|
make.m
|
.m
|
Programs-master/matlab/cvx/examples/make.m
| 23,079 |
utf_8
|
8b04233b872cb2ab50851644ae0e486a
|
function make( varargin )
%
% Determine the base path
%
odir = pwd;
base = mfilename('fullpath');
base = fileparts( base );
%
% Check the force and runonly flags
%
args = varargin;
is_octave = exist( 'OCTAVE_VERSION', 'builtin' );
if is_octave,
force = true;
runonly = true;
indexonly = false;
page_output_immediately(true);
else
temp = strcmp( args, '-force' );
force = any( temp );
if force, args(temp) = []; end
temp = strcmp( args, '-runonly' );
runonly = any( temp );
if runonly, args(temp) = []; end
temp = strcmp( args, '-indexonly' );
indexonly = any( temp );
if indexonly, args(temp) = []; end
if ~runonly,
close all;
fclose all;
end
end
if isempty( args ),
args = { base };
end
%
% Process the arguments
%
for k = 1 : length( args ),
file = args{k};
if any( file == '*' ),
files = dir( file );
files = { files.name };
else
files = { file };
end
for j = 1 : length( files );
%
% Check the validity of the file or directory
%
file = files{j};
switch exist( file, 'file' ),
case 0,
error( 'Cannot find file or directory: %s', file );
case 2,
file = which( file );
if isempty( file ),
file = files{j};
if file(1) ~= filesep,
file = [ base, filesep, file ];
end
end
[ mpath, file, ext ] = fileparts( file );
file = [ file, ext ];
if ~strcmp( ext, '.m' ),
error( 'Must be an m-file: %s' );
elseif strcmp( file, 'Contents.m' ) && length( files ) > 1,
continue;
elseif strcmp( file, 'make.m' ) && strcmp( mpath, base ),
continue;
end
case 7,
cd( file );
mpath = pwd;
cd( odir );
file = '';
otherwise,
error( 'Invalid file: %s', file );
end
if length( mpath ) < length( base ) || strncmpi( mpath, base, length( base ) ) == 0,
error( 'Not a valid a subdirectory of cvx/examples/: %s', mpath );
end
%
% Process the file or directory
%
if ~runonly && isempty( file ) && strcmp( mpath, base ),
[ fidr, message ] = fopen( 'index.html', 'r' );
if fidr < 0,
error( 'Cannot open index.html\n %s', message );
end
[ fidw, message ] = fopen( 'index.html.new', 'w+' );
if fidw < 0,
error( 'Cannot open index.html.new\n %s', message );
end
while ~feof( fidr ),
temp = fgetl( fidr );
fprintf( fidw, '%s\n', temp );
if strcmp(temp,'<ul class="mktree" id="tree1">'),
while ~feof( fidr ),
temp = fgetl( fidr );
if strcmp(temp,'</ul>'), break; end
end
break;
end
end
else
fidw = -1;
end
if isempty( file ),
generate_directory( mpath, '', force, runonly, indexonly, fidw, base, 0, is_octave );
else
cd( mpath );
generate_file( file, '', force, runonly, indexonly, is_octave );
end
cd( odir );
if fidw >= 0,
fprintf( fidw, '</ul>\n' );
while ~feof( fidr ),
fprintf( fidw, '%s\n', fgetl( fidr ) );
end
fclose( fidr );
fclose( fidw );
cd( mpath )
compare_and_replace( '', 'index.html' );
end
end
end
function [ title, files ] = generate_directory( mpath, prefix, force, runonly, indexonly, fidc, base, depth, is_octave )
fprintf( 1, '%sDirectory: %s\n', prefix, mpath );
prefix = [ prefix, ' ' ];
cd( mpath );
mpath = pwd;
%
% Open Contents.m file and retrieve title and comments
%
title = '';
if ~runonly,
comments = {};
fcomments = {};
[ fidr, message ] = fopen( 'Contents.m', 'r' );
if fidr >= 0,
temp = fgetl( fidr );
if length( temp ) > 2 && temp( 1 ) == '%' && temp( 2 ) == ' ' && temp( 3 ) ~= ' ',
title = temp( min( find( temp ~= '%' & temp ~= ' ' ) ) : end );
while ~feof( fidr ),
temp = fgetl( fidr );
if isempty(temp) || temp( 1 ) ~= '%' || ~any( temp ~= '%' & temp ~= ' ' ), break; end
temp = temp( min( find( temp ~= '%' & temp ~= ' ' ) ) : end );
if strcmp(title(end-2:end),'...'),
title = [ title(1:end-3), temp ];
else
if ~isempty(fcomments) && strcmp( fcomments{end}(end-2:end),'...' ),
fcomments{end} = [ fcomments{end}(1:end-3), temp ];
else
fcomments{end+1} = temp;
end
comments{end+1} = temp;
end
end
end
fclose( fidr );
elseif ~isempty( dir( 'Contents.m' ) ),
error( 'Cannot open Contents.m for reading\n %s', message );
end
end
if isempty(title),
title = '(no title)';
end
%
% Read the entries, and process the scripts and functions
%
dd = dir;
mlen = 0;
files = struct( 'name', {}, 'title', {}, 'type', {} );
for k = 1 : length( dd ),
name = dd(k).name;
if dd(k).isdir,
if name(1) == '.' || strcmp( name, 'eqs' ) || strcmp( name, 'html' ), continue; end
name(end+1) = '/';
files( end + 1 ) = struct( 'name', name, 'title', '', 'type', 'dir' );
elseif length( name ) > 2,
ndx = max(find(name=='.'));
if isempty( ndx ), continue; end
switch name(ndx+1:end),
case 'm',
if strcmp( name, 'Contents.m' ) || strcmp( name, 'make.m' ) || name(end-2) == '_', continue; end
[ temp, isfunc ] = generate_file( name, prefix, force, runonly, indexonly, is_octave );
if isfunc, type = 'func'; else type = 'script'; end
files( end + 1 ) = struct( 'name', name, 'title', temp, 'type', type );
case 'tex',
temp = generate_doc( name, prefix, force );
files( end + 1 ) = struct( 'name', name, 'title', temp, 'type', 'tex' );
case { 'pdf', 'ps' },
if any( strcmp( { dd.name }, [name(1:ndx+1),'tex'] ) ), continue; end
files( end + 1 ) = struct( 'name', name, 'title', '', 'type', 'doc' );
case { 'dat', 'mat', 'txt' },
if strcmp( name, 'index.dat' ), continue; end
files( end + 1 ) = struct( 'name', name, 'title', '', 'type', 'dat' );
otherwise,
continue;
end
end
mlen = max( mlen, length(name) );
end
%
% Sort the files
%
if ~isempty( files ),
[ fnames, ndxs ] = sort( { files.title } );
files = files(ndxs);
ftypes = { files.type };
tdir = strcmp( ftypes, 'dir' );
tfun = strcmp( ftypes, 'func' );
tdoc = strcmp( ftypes, 'doc' ) | strcmp( ftypes, 'tex' );
tdat = strcmp( ftypes, 'dat' );
tscr = ~( tdir | tfun | tdoc | tdat );
t1 = strncmp( fnames, 'Exercise', 8 ) & tscr;
t2 = strncmp( fnames, 'Example', 7 ) & tscr;
t3 = strncmp( fnames, 'Section', 7 ) & tscr;
t4 = strncmp( fnames, 'Figure', 6 ) & tscr;
t5 = ~( t1 | t2 | t3 | t4 ) & tscr;
tdir = find(tdir(:));
tscr = [ find(t3(:)); find(t4(:)); find(t2(:)); find(t5(:)); find(t1(:)); ];
tfun = find(tfun(:));
tdoc = find(tdoc(:));
tdat = find(tdat(:));
files = files( [ tdoc ; tdir ; tscr ; tfun ; tdat ] );
tdoc = [ 1, length(tdoc) ];
tdir = tdoc(end) + [ 1, length(tdir) ];
tscr = tdir(end) + [ 1, length(tscr) ];
tfun = tscr(end) + [ 1, length(tfun) ];
tdat = tfun(end) + [ 1, length(tdat) ];
end
%
% Fill out the index.jemdoc file
%
if fidc >= 0,
dots = sprintf('\t');
dots = dots(ones(1,depth+1));
dpath = mpath( length(base) + 2 : end );
dpath(dpath=='\') = '/';
if ~isempty(dpath), dpath(end+1) = '/'; end
% Directory title---skip for the top level
if depth,
title = regexprep(title,'</?b>','');
title = regexprep(title,' target="_blank"','');
title2 = regexprep(title,'<a ([^>]*>)','</b><a target="_blank" $1<b>');
title2 = regexprep(title2,'</a>','</b></a><b>');
title2 = regexprep(['<b>',title2,'</b>'],'<b></b>','');
fprintf( fidc, '%s<li>%s<ul>\n', dots(1:end-1), title2 );
end
if tdoc(2) >= tdoc(1) || ~isempty( fcomments ),
for k = tdoc(1) : tdoc(2),
name = files( k ).name;
if strcmp( files(k).type, 'tex' ),
name = [ name(1:end-4), 'pdf' ];
end
temp = files( k ).title;
if isempty( temp ),
fprintf( fidc, '%s<li>Reference: <a href="%s%s" target="_blank">%s</a></li>\n', dots, dpath, name, name );
else
fprintf( fidc, '%s<li>Reference: <a href="%s%s" target="_blank">%s (%s)</a></li>\n', dots, dpath, name, temp, name );
end
end
for k = 1 : length(fcomments),
fprintf( fidc, '%s<li>Reference: %s</li>\n', dots, regexprep(fcomments{k},'<a href=','<a target="_blank" href='));
end
end
for k = tdir(1) : tdir(2),
files(k).title = generate_directory( files(k).name(1:end-1), prefix, force, runonly, indexonly, fidc, base, depth+1, is_octave );
cd(mpath);
end
if tscr(2) >= tscr(1),
if ~depth,
fprintf( fidc, '%s<li><b>Miscellaneous examples</b>\n', dots );
dots(end+1) = dots(end);
fprintf( fidc, '%s<ul>\n', dots );
end
for k = tscr(1) : tscr(2),
name = files( k ).name;
temp = files( k ).title;
if isempty( temp ),
fprintf( fidc, '%s<li><a href="%s%s">%s</a></li>\n', dots, dpath, name, name );
else
fprintf( fidc, '%s<li><a href="%shtml/%shtml">%s</a> (<a href="%s%s">%s</a>)</li>\n', dots, dpath, name(1:end-1), temp, dpath, name, name );
end
end
if ~depth,
fprintf( fidc, '%s</ul>\n', dots );
dots(end) = [];
fprintf( fidc, '%s</li>\n', dots );
end
end
if tfun(2) >= tfun(1),
pref = 'Utility: ';
for k = tfun(1) : tfun(2),
name = files( k ).name;
temp = files( k ).title;
if isempty( temp ),
fprintf( fidc, '%s<li>Utility: <a href="%s%s">%s</a></li>\n', dots, dpath, name, name );
else
fprintf( fidc, '%s<li>Utility: <a href="%shtml/%shtml">%s</a> (<a href="%s%s">%s</a>)</li>\n', dots, dpath, name(1:end-1), temp, dpath, name, name );
end
end
end
if tdat(2) >= tdat(1),
pref = '- Data: ';
for k = tdat(1) : tdat(2),
name = files( k ).name;
temp = files( k ).title;
if isempty( temp ),
fprintf( fidc, '%s<li>Data: <a href="%s%s">%s</a></li>\n', dots, dpath, name, name );
else
fprintf( fidc, '%s<li>Data: <a href="%s%s">%s (%s)</a></li>\n', dots, dpath, name, temp, name );
end
end
end
if depth,
fprintf( fidc, '%s</ul></li>\n', dots(1:end-1) );
end
elseif any( tdir ),
for k = 1 : length( files ),
if strcmp( files(k).type, 'dir' ),
files(k).title = generate_directory( files(k).name(1:end-1), prefix, force, runonly, indexonly, fidc, base, depth+1, is_octave );
cd(mpath);
end
end
end
%
% Create Contents.m.new
%
if ~runonly,
[ fidw, message ] = fopen( 'Contents.m.new', 'w+' );
if fidw < 0,
if fidr >= 0, fclose( fidr ); end
error( 'Cannot open Contents.m.new\n %s', message );
elseif ~isempty( title ),
fprintf( fidw, '%% %s\n', title );
for k = 1 : length( comments ),
fprintf( fidw, '%% %s\n', comments{k} );
end
fprintf( fidw, '%%\n' );
end
for k = 1 : length( files ),
tfile = files(k);
tfile.name(end+1:mlen) = ' ';
if isempty( tfile.title ),
fprintf( fidw, '%% %s - (no title)\n', tfile.name );
else
fprintf( fidw, '%% %s - %s\n', tfile.name, tfile.title );
end
end
fprintf( fidw, 'help Contents\n' );
fclose( fidw );
else
fidw = -1;
end
%
% Compare Contents.m and Contents.m.new and update if necessary
%
cd( mpath )
if fidw >= 0,
compare_and_replace( prefix, 'Contents.m' );
end
function [ title, isfunc ] = generate_file( name, prefix, force, runonly, indexonly, is_octave )
if length( name ) < 2 || ~strcmp( name(end-1:end), '.m' ),
error( 'Not an m-file.' );
elseif strcmp( name, 'Contents.m' ),
error( 'To generate the Contents.m file, you must run this function on the entire directory.' );
else
fprintf( 1, '%s%s: ', prefix, name );
end
dd = dir( name );
ndate = date_convert( dd.date );
[ fidr, message ] = fopen( name, 'r' );
if fidr < 0,
error( 'Cannot open the source file\n %s', message );
end
title = '';
isfunc = false;
lasttitle = false;
founddata = false;
prefixes = {};
while ~feof( fidr ) && ( ~founddata || isempty( title ) || lasttitle ),
temp1 = fgetl( fidr );
if isempty( temp1 ),
if lasttitle, continue; end
else
temp2 = find( temp1 ~= ' ' );
if isempty( temp2 ),
if lasttitle, continue; end
elseif temp1(temp2(1)) == '%',
temp2 = temp1(temp2(1):temp2(end));
temp3 = find( temp2 ~= '%' );
if isempty( temp3 ),
if lasttitle, continue; end
else
temp3 = temp2( temp3(1) : end );
temp4 = find( temp3 ~= ' ' );
if isempty( temp4 ),
if lasttitle, continue; end
elseif isempty( title ),
title = temp3(temp4(1):temp4(end));
lasttitle = true;
continue;
else
lasttitle = false;
end
end
else
lasttitle = false;
founddata = true;
temp2 = temp1(temp2(1):temp2(end));
if strncmp( temp2, 'function', 8 ) && ( length( temp2 ) == 8 || ~isvarname( temp2( 1 : 9 ) ) ),
isfunc = true;
end
end
end
prefixes{end+1} = temp1;
end
if runonly,
fclose( fidr );
if isfunc, return; end
end
hfile = [ name(1:end-1), 'html' ];
odir = pwd;
hdir = 'html';
hdate = 0;
if exist( hdir, 'dir' ),
cd( hdir );
df = dir( hfile );
if length( df ) == 1,
hdate = date_convert( df.date );
end
cd( odir );
end
if indexonly,
fprintf( 1, 'done.\n' );
elseif force || hdate <= ndate,
if runonly,
fprintf( 1, 'running %s ...', name );
elseif hdate == 0,
fprintf( 1, 'creating %s ...', hfile );
else
fprintf( 1, 'updating %s ...', hfile );
end
name = name(1:end-2);
if ~runonly,
[ fidw, message ] = fopen( [ name, '_.m' ], 'w+' );
if fidw < 0,
error( 'Cannot open the temporary file\n %s', message );
end
if isempty( title ),
fprintf( fidw, '%%%% %s\n\n', name );
else
fprintf( fidw, '%%%% %s\n\n', title );
end
fprintf( fidw, '%s\n', prefixes{:} );
fwrite( fidw, fread( fidr, Inf, 'uint8' ), 'uint8' );
fclose( fidw );
fclose( fidr );
end
evalin( 'base', 'clear' );
cvx_clear;
cvx_quiet( false );
cvx_precision default;
success = true;
try
out___ = [];
if is_octave,
run_clean_octave( name );
elseif runonly,
out___ = run_clean( name );
fprintf( 1, ' done.\n' );
else
opts.format = 'html';
opts.useNewFigure = false;
opts.createThumbnail = false;
opts.evalCode = ~isfunc;
opts.showCode = true;
opts.catchError = false;
publish( [ name, '_' ], opts );
prefixes = { '<style', '<!--', '<p class="footer"', '<meta name=', '<link rel=' };
suffixes = { '</style>', '-->', '</p>', '>', '>' };
suffix = '';
f_in = fopen( [ 'html', filesep, name, '_.html' ], 'r' );
data = fread( f_in, Inf, 'uint8=>char' )';
fclose( f_in );
backpath = '';
for k = 1 : 10,
if exist( [ backpath, filesep, 'examples.css' ], 'file' ), break; end
backpath = [ '..', filesep, backpath ];
end
backpath = [ '..', filesep, backpath ];
canon = [regexprep(pwd,'.*/cvx/examples','http://cvxr.com/cvx/examples'),'/html/',hfile];
data = regexprep( data, '<!--.*?-->|<link rel=.*?>|<style.*?</style>|<meta name=.*?>|<p class="footer".*?</p>', '' );
data = regexprep( data, '</head>', sprintf( '\n<link rel="canonical" href="%s"/>\n<link rel="stylesheet" href="%sexamples.css" type="text/css"/>\n</head>', canon, backpath ) );
data = regexprep( data, '<div class="content"><h1>(.*?)</h1>','<div id="header">\n<h1>$1</h1>\n<!--control--></div><div id="content">' );
data = regexprep( data, '<pre class="codeinput">\n?', '\n<a id="source"></a><pre class="codeinput">\n' );
if ~isempty( regexp( data, '<pre class="codeoutput">' ) ),
control_o = '<a href="#output">Text output</a>\n';
data = regexprep( data, '<pre class="codeoutput">\n?', '\n<a id="output"></a><pre class="codeoutput">\n' );
else
control_o = 'Text output\n';
end
if ~isempty( regexp( data, '</pre>\s*<img', 'once' ) ),
control_p = '<a href="#plots">Plots</a>\n';
data = regexprep( data, '</pre>\s*<img', '</pre>\n<a id="plots"></a><div id="plotoutput">\n<img' );
data = regexprep( data, '</div>\s*</body>', '</div></div></body>' );
else
control_p = 'Plots\n';
end
control = sprintf( 'Jump to: \n<a href="#source">Source code</a> \n%s \n%s <a href="%sindex.html">Library index</a>', control_o, control_p, backpath );
data = regexprep( data, '<!--control-->', control );
data = regexprep( data, '<html>', '<html>\n' );
data = regexprep( data, '(<div|<pre|</div>|<body>|</body>|</html>)', '\n$1' );
data = regexprep( data, '^\s*<!DOCTYPE.*?>','<!DOCTYPE HTML>' );
data = regexprep( data, '<meta http-equiv.*?>', '<meta charset="UTF-8">' );
data = regexprep( data, '\s*((v|h)space=\S*)', '' );
data = regexprep( data, '\s*(<meta|<title)','\n$1' );
data = regexprep( data, '/>', '>' );
f_out = fopen( [ 'html', filesep, name, '.html' ], 'w' );
fwrite( f_out, data );
fclose( f_out );
delete( [ 'html', filesep, name, '_.html' ] );
fprintf( 1, ' done.\n' );
end
catch
err = lasterror;
fprintf( 1, ' aborted.\n' );
cd( odir );
fprintf( 1, '===> ERROR: %s\n', err.message );
success = false;
end
if runonly,
disp( out___ );
else
delete( [ name, '_.m' ] );
end
cd( odir );
if ~success && ~runonly && exist( hdir, 'dir' ),
cd( hdir );
df = dir( hfile );
if length( df ) == 1,
delete( hfile );
end
cd( odir );
end
close all
else
fprintf( 1, 'up to date.\n' );
end
function title = generate_doc( name, prefix, force )
if length( name ) < 5 || ~strcmp( name(end-3:end), '.tex' ),
error( 'Not an valid TeX file.' );
else
fprintf( 1, '%s%s: ', prefix, name );
end
dd = dir( name );
ndate = date_convert( dd.date );
[ fidr, message ] = fopen( name, 'r' );
if fidr < 0,
error( 'Cannot open the source file\n %s', message );
end
title = '';
while ~feof( fidr ),
temp = strtrim( fgetl( fidr ) );
kndx = strfind( temp, '\title{' );
if isempty( kndx ), continue; end
knd2 = strfind( temp(kndx(1):end), '}' );
if isempty( knd2 ), continue; end
title = strtrim(temp(kndx(1)+7:kndx(1)+kndx(2)-2));
break;
end
pdffile = [ name(1:end-3), 'pdf' ];
hdate = 0;
df = dir( pdffile );
if length( df ) == 1,
hdate = date_convert( df.date );
end
if force || hdate < ndate,
if hdate == 0,
fprintf( 1, 'creating %s:', hfile );
else
fprintf( 1, 'updating %s:', hfile );
end
name2 = name(1:end-4);
eval( sprintf( '!latex %s', name2 ) );
eval( sprintf( '!latex %s', name2 ) );
eval( sprintf( '!bibtex %s', name2 ) );
eval( sprintf( '!latex %s', name2 ) );
eval( sprintf( '!latex %s', name2 ) );
eval( sprintf( '!latex %s', name2 ) );
eval( sprintf( '!dvips %s', name2 ) );
eval( sprintf( '!ps2pdf %s.ps', name2 ) );
end
function dnum = date_convert( dstr )
persistent mstrs
if isempty( mstrs ),
mstrs = { 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' };
end
% DD-MMM-YY HH:MM:SS
S = sscanf( dstr, '%d-%3s-%d %d:%d:%d' );
S = [ S(5), find(strcmp(char(S(2:4)'),mstrs)), S(1), S(6), S(7), S(8) ];
dnum = S(6) + 100 * ( S(5) + 100 * ( S(4) + 100 * ( S(3) + 100 * ( S(2) + 100 * S(1) ) ) ) );
function compare_and_replace( prefix, oldname )
names = { oldname, [ oldname, '.new' ] };
fprintf( 1, '%s%s ... ', prefix, oldname );
fids = [];
c = {};
for k = 1 : 2,
[ fids(k), message ] = fopen( names{k}, 'r' );
if fids(k) < 0 && ~isempty( dir( names{k} ) ),
error( 'Cannot open file %s for reading:\n %s', names{k}, message );
end
c{k} = fread( fids(k), Inf, 'uint8' );
fclose( fids(k) );
end
if isempty( c{2} ),
if fids(k) >= 0,
fprintf( 1, ' removed.\n' );
delete( oldname );
end
delete( names{2} );
elseif length( c{1} ) ~= length( c{2} ) || any( c{1} ~= c{2} ),
[ success, message ] = movefile( names{2}, names{1}, 'f' );
if ~success,
error( 'Cannot move %s into place\n %s', names{2}, message );
delete( names{2} )
end
if ~isempty( c{1} ),
fprintf( 1, ' updated.\n' );
else
fprintf( 1, ' created.\n' );
end
else
delete( names{2} )
fprintf( 1, ' up to date.\n' );
end
function run_clean_octave( name )
feval( name );
function out___ = run_clean( name )
out___ = evalc( name );
|
github
|
xiaoxiaojiangshang/Programs-master
|
cantilever_beam_plot.m
|
.m
|
Programs-master/matlab/cvx/examples/cvxbook/Ch04_cvx_opt_probs/cantilever_beam_plot.m
| 1,050 |
utf_8
|
e8c8c9e1b601e4102f96e0436649d132
|
% Plots a cantilever beam as a 3D figure.
% This is a helper function for the optimal cantilever beam example.
%
% Inputs:
% values: an array of heights and widths of each segment
% [h1 h2 ... hN w1 w2 ... wN]
%
% Almir Mutapcic 01/25/06
function cantilever_beam_plot(values)
N = length(values)/2;
for k = 0:N-1
[X Y Z] = data_rect3(values(2*N-k),values(N-k),k);
plot3(X,Y,Z); hold on;
end
hold off;
xlabel('width')
ylabel('height')
zlabel('length')
return;
%****************************************************************
function [X, Y, Z] = data_rect3(w,h,d)
%****************************************************************
% back face
X = [-w/2 w/2 w/2 -w/2 -w/2];
Y = [-h/2 -h/2 h/2 h/2 -h/2];
Z = [d d d d d];
% side face
X = [X -w/2 -w/2 -w/2 -w/2 -w/2];
Y = [Y -h/2 -h/2 h/2 h/2 -h/2];
Z = [Z d d+1 d+1 d d];
% front face
X = [X -w/2 w/2 w/2 -w/2 -w/2];
Y = [Y -h/2 -h/2 h/2 h/2 -h/2];
Z = [Z d+1 d+1 d+1 d+1 d+1];
% back side face
X = [X w/2 w/2 w/2 w/2 w/2];
Y = [Y -h/2 h/2 h/2 -h/2 -h/2];
Z = [Z d+1 d+1 d d d+1];
|
github
|
xiaoxiaojiangshang/Programs-master
|
simple_step.m
|
.m
|
Programs-master/matlab/cvx/examples/circuit_design/simple_step.m
| 235 |
utf_8
|
b8043326fe5966f9432b69b584891e0f
|
% Computes the step response of a linear system
function X = simple_step(A,B,DT,N)
n = size(A,1);
Ad = expm( full( A * DT ) );
Bd = ( Ad - eye(n) ) * B;
Bd = A \ Bd;
X = zeros(n,N);
for k = 2 : N,
X(:,k) = Ad*X(:,k-1)+Bd;
end
|
github
|
xiaoxiaojiangshang/Programs-master
|
spectral_fact.m
|
.m
|
Programs-master/matlab/cvx/examples/filter_design/spectral_fact.m
| 1,292 |
utf_8
|
014eebfa2dfbbd038c1383ff2ef97b0e
|
% Spectral factorization using Kolmogorov 1939 approach.
% (code follows pp. 232-233, Signal Analysis, by A. Papoulis)
%
% Computes the minimum-phase impulse response which satisfies
% given auto-correlation.
%
% Input:
% r: top-half of the auto-correlation coefficients
% starts from 0th element to end of the auto-corelation
% should be passed in as a column vector
% Output
% h: impulse response that gives the desired auto-correlation
function h = spectral_fact(r)
% length of the impulse response sequence
n = length(r);
% over-sampling factor
mult_factor = 100; % should have mult_factor*(n) >> n
m = mult_factor*n;
% computation method:
% H(exp(jTw)) = alpha(w) + j*phi(w)
% where alpha(w) = 1/2*ln(R(w)) and phi(w) = Hilbert_trans(alpha(w))
% compute 1/2*ln(R(w))
w = 2*pi*[0:m-1]/m;
R = [ ones(m,1) 2*cos(kron(w',[1:n-1])) ]*r;
alpha = 1/2*log(R);
% find the Hilbert transform
alphatmp = fft(alpha);
alphatmp(floor(m/2)+1:m) = -alphatmp(floor(m/2)+1:m);
alphatmp(1) = 0;
alphatmp(floor(m/2)+1) = 0;
phi = real(ifft(j*alphatmp));
% now retrieve the original sampling
index = find(rem([0:m-1],mult_factor)==0);
alpha1 = alpha(index);
phi1 = phi(index);
% compute the impulse response (inverse Fourier transform)
h = real(ifft(exp(alpha1+j*phi1),n));
|
github
|
xiaoxiaojiangshang/Programs-master
|
polar_plot_ant.m
|
.m
|
Programs-master/matlab/cvx/examples/antenna_array_design/polar_plot_ant.m
| 1,149 |
utf_8
|
34a08a3bc75c474d61e01ea58b16e54e
|
% Plot a polar plot of an antenna array sensitivity
% with lines denoting the target direction and beamwidth.
% This is a helper function used in the broadband antenna examples.
%
% Inputs:
% X: an array of abs(y(theta)) where y is the antenna array pattern
% theta0: target direction
% bw: total beamwidth
% label: a string displayed as the plot legend
%
% Original code by Lieven Vandenberghe
% Updated for CVX by Almir Mutapcic 02/17/06
function polar_plot_ant(X,theta0,bw,label)
% polar plot
numpoints = length(X);
thetas2 = linspace(1,360,numpoints)';
plot(X.*cos(pi*thetas2/180), X.*sin(pi*thetas2/180), '-');
plot(X.*cos(pi*thetas2/180), X.*sin(pi*thetas2/180), '-');
hold on;
axis('equal');
plot(cos(pi*[thetas2;1]/180), sin(pi*[thetas2;1]/180), '--');
text(1.1,0,'1');
plot([0 cos(pi*theta0/180)], [0 sin(pi*theta0/180)], '--');
sl1 = find(thetas2-theta0 > bw/2);
sl2 = find(thetas2-theta0 < -bw/2);
Gsl = max(max(X(sl1)), max(X(sl2)));
plot(Gsl*cos(pi*thetas2(sl1)/180), Gsl*sin(pi*thetas2(sl1)/180), '--');
plot(Gsl*cos(pi*thetas2(sl2)/180), Gsl*sin(pi*thetas2(sl2)/180), '--');
text(-1,1.1,label);
axis off;
|
github
|
xiaoxiaojiangshang/Programs-master
|
spectral_fact.m
|
.m
|
Programs-master/matlab/cvx/examples/antenna_array_design/spectral_fact.m
| 1,385 |
utf_8
|
570e7ae2165d19abd477494c52e609f8
|
% Spectral factorization using Kolmogorov 1939 approach
% (code follows pp. 232-233, Signal Analysis, by A. Papoulis)
%
% Computes the minimum-phase impulse response which satisfies
% given auto-correlation.
%
% Input:
% r: top-half of the auto-correlation coefficients
% starts from 0th element to end of the auto-corelation
% should be passed in as a column vector
% Output
% h: impulse response that gives the desired auto-correlation
function h = spectral_fact(r)
% length of the impulse response sequence
nr = length(r);
n = (nr+1)/2;
% over-sampling factor
mult_factor = 30; % should have mult_factor*(n) >> n
m = mult_factor*n;
% computation method:
% H(exp(jTw)) = alpha(w) + j*phi(w)
% where alpha(w) = 1/2*ln(R(w)) and phi(w) = Hilbert_trans(alpha(w))
% compute 1/2*ln(R(w))
w = 2*pi*[0:m-1]/m;
R = exp( -j*kron(w',[-(n-1):n-1]) )*r;
R = abs(real(R)); % remove numerical noise from the imaginary part
figure; plot(20*log10(R));
alpha = 1/2*log(R);
% find the Hilbert transform
alphatmp = fft(alpha);
alphatmp(floor(m/2)+1:m) = -alphatmp(floor(m/2)+1:m);
alphatmp(1) = 0;
alphatmp(floor(m/2)+1) = 0;
phi = real(ifft(j*alphatmp));
% now retrieve the original sampling
index = find(rem([0:m-1],mult_factor)==0);
alpha1 = alpha(index);
phi1 = phi(index);
% compute the impulse response (inverse Fourier transform)
h = ifft(exp(alpha1+j*phi1),n);
|
github
|
xiaoxiaojiangshang/Programs-master
|
plotgraph.m
|
.m
|
Programs-master/matlab/cvx/examples/graph_laplacian/plotgraph.m
| 3,172 |
utf_8
|
a46b1d761798c492e96a5b9504aea9aa
|
function plotgraph(A,xy,weights)
% Plots a graph with each edge width proportional to its weight.
%
% Edges with positive weights are drawn in blue; negative weights in red.
%
% Input parameters:
% A --- incidence matrix of the graph (size is n x m)
% (n is the number of nodes and m is the number of edges)
% xy --- horizontal and vertical positions of the nodes (n x 2 matrix)
% weights --- m vector giving edge weights
%
% Original by Lin Xiao
% Modified by Almir Mutapcic
% graph size
[n,m]= size(A);
% set the graph scale and normalize the coordinates to lay in [-1,1] square
R = max(max(abs(xy))); % maximum abs value of the xy coordinates
x = xy(:,1)/R; y = xy(:,2)/R;
% normalize weight vector to range between +1 and -1
weights = weights/max(abs(weights));
% internal parameters (tune these parameters to make the plot look pretty)
% (note that the graph coordinates and the weights have been rescaled
% to a common unity scale)
%rNode = 0.005; % radius of the node circles
rNode = 0; % set the node radius to zero if you do not want the nodes
wNode = 2; % line width of the node circles
PWColor = [0 0 1]; % color of the edges with positive weights
NWColor = [1 0 0]; % color of the edges with negative weights
Wmin = 0.0001; % minimum weight value for which we draw an edge
max_width = 0.05; % drawn width of edge with maximum absolute weight
% first draw the edges with patch widths proportional to the weights
for i=1:m
if ( abs(weights(i)) > Wmin )
Isrc = find( sign(weights(i))*A(:,i)>0 );
Idst = find( sign(weights(i))*A(:,i)<0 );
else
Isrc = find( A(:,i)>0 );
Idst = find( A(:,i)<0 );
end
% obtain edge patch coordinates
xdelta = x(Idst) - x(Isrc); ydelta = y(Idst) - y(Isrc);
RotAgl = atan2( ydelta, xdelta );
xstart = x(Isrc) + rNode*cos(RotAgl); ystart = y(Isrc) + rNode*sin(RotAgl);
xend = x(Idst) - rNode*cos(RotAgl); yend = y(Idst) - rNode*sin(RotAgl);
L = sqrt( xdelta^2 + ydelta^2 ) - 2*rNode;
if ( weights(i) > Wmin )
W = abs(weights(i))*max_width;
drawedge(xstart, ystart, RotAgl, L, W, PWColor);
hold on;
elseif ( weights(i) < -Wmin )
W = abs(weights(i))*max_width;
drawedge(xstart, ystart, RotAgl, L, W, NWColor);
hold on;
else
plot([xstart xend],[ystart yend],'k:','LineWidth',2.5);
end
end
% the circle to draw around each node
angle = linspace(0,2*pi,100);
xbd = rNode*cos(angle);
ybd = rNode*sin(angle);
% draw the nodes
for i=1:n
plot( x(i)+xbd, y(i)+ybd, 'k', 'LineWidth', wNode );
end;
axis equal;
set(gca,'Visible','off');
hold off;
%********************************************************************
% helper function to draw edges in the graph
%********************************************************************
function drawedge( x0, y0, RotAngle, L, W, color )
xp = [ 0 L L L L L 0 0 ];
yp = [-0.5*W -0.5*W -0.5*W 0 0.5*W 0.5*W 0.5*W -0.5*W];
RotMat = [cos(RotAngle) -sin(RotAngle); sin(RotAngle) cos(RotAngle)];
DrawCoordinates = RotMat*[ xp; yp ];
xd = x0 + DrawCoordinates(1,:);
yd = y0 + DrawCoordinates(2,:);
% draw the edge
patch( xd, yd, color );
|
github
|
xiaoxiaojiangshang/Programs-master
|
disp.m
|
.m
|
Programs-master/matlab/cvx/lib/@cvxprob/disp.m
| 5,405 |
utf_8
|
c8f4506efcff564b81f1f3cc1dbb8a9c
|
function disp( prob, prefix )
if nargin < 2, prefix = ''; end
global cvx___
p = cvx___.problems( prob.index_ );
if isempty( p.variables ),
nvars = 0;
else
nvars = length( fieldnames( p.variables ) );
end
if isempty( p.duals ),
nduls = 0;
else
nduls = length( fieldnames( p.duals ) );
end
neqns = ( length( cvx___.equalities ) - p.n_equality ) + ...
( length( cvx___.linforms ) - p.n_linform ) + ...
( length( cvx___.uniforms ) - p.n_uniform );
nineqs = nnz( cvx___.needslack( p.n_equality + 1 : end ) ) + ...
nnz( cvx_vexity( cvx___.linrepls( p.n_linform + 1 : end ) ) ) + ...
nnz( cvx_vexity( cvx___.unirepls( p.n_uniform + 1 : end ) ) );
neqns = neqns - nineqs;
if isempty( p.name ) || strcmp( p.name, 'cvx_' ),
nm = '';
else
nm = [ p.name, ': ' ];
end
rsv = cvx___.reserved;
nt = length( rsv );
fv = length( p.t_variable );
qv = fv + 1 : nt;
tt = p.t_variable;
ni = nnz( tt ) - 1;
ndup = sum( rsv ) - nnz( rsv );
neqns = neqns + ndup;
nv = nt - fv + ni + ndup;
tt( qv ) = true;
gfound = nnz( cvx___.logarithm( tt ) );
cfound = false;
for k = 1 : length( cvx___.cones ),
if any( any( tt( cvx___.cones( k ).indices ) ) ),
cfound = true;
break;
end
end
if all( [ numel( p.objective ), nv, nvars, nduls, neqns, nineqs, cfound, gfound ] == 0 ),
disp( [ prefix, nm, 'cvx problem object' ] );
else
if ( p.gp ),
ptype =' geometric ';
elseif ( p.sdp ),
ptype = ' semidefinite ';
else
ptype = ' ';
end
if isempty( p.objective ),
tp = 'feasibility';
else
switch p.direction,
case 'minimize', tp = 'minimization';
case 'epigraph', tp = 'epigraph minimization';
case 'hypograph', tp = 'hypograph maximization';
case 'maximize', tp = 'maximization';
end
if numel( p.objective ) > 1,
sz = sprintf( '%dx', size( p.objective ) );
tp = [ sz(1:end-1), '-objective ', tp ];
end
end
disp( [ prefix, nm, 'cvx', ptype, tp, ' problem' ] );
if nvars > 0,
disp( [ prefix, 'variables: ' ] );
[ vnam, vsiz ] = dispvar( p.variables, '' );
vnam = strvcat( vnam ); %#ok
vsiz = strvcat( vsiz ); %#ok
for k = 1 : size( vnam ),
disp( [ prefix, ' ', vnam( k, : ), ' ', vsiz( k, : ) ] );
end
end
if nduls > 0,
disp( [ prefix, 'dual variables: ' ] );
[ vnam, vsiz ] = dispvar( p.duals, '' );
vnam = strvcat( vnam ); %#ok
vsiz = strvcat( vsiz ); %#ok
for k = 1 : size( vnam ),
disp( [ prefix, ' ', vnam( k, : ), ' ', vsiz( k, : ) ] );
end
end
if neqns > 0 || nineqs > 0,
disp( [ prefix, 'linear constraints:' ] );
if neqns > 0,
if neqns > 1, plural = 'ies'; else plural = 'y'; end
fprintf( 1, '%s %d equalit%s\n', prefix, neqns, plural );
end
if nineqs > 0,
if nineqs > 1, plural = 'ies'; else plural = 'y'; end
fprintf( 1, '%s %d inequalit%s\n', prefix, nineqs, plural );
end
end
if cfound || gfound,
disp( [ prefix, 'nonlinearities:' ] );
if gfound > 0,
if gfound > 1, plural = 's'; else plural = ''; end
fprintf( 1, '%s %d exponential pair%s\n', prefix, gfound, plural );
end
if cfound,
for k = 1 : length( cvx___.cones ),
ndxs = cvx___.cones( k ).indices;
ndxs = ndxs( :, any( reshape( tt( ndxs ), size( ndxs ) ), 1 ) );
if ~isempty( ndxs ),
if isequal( cvx___.cones( k ).type, 'nonnegative' ),
ncones = 1;
csize = numel( ndxs );
else
[ csize, ncones ] = size( ndxs );
end
if ncones == 1, plural = ''; else plural = 's'; end
fprintf( 1, '%s %d order-%d %s cone%s\n', prefix, ncones, csize, cvx___.cones( k ).type, plural );
end
end
end
end
end
function [ names, sizes ] = dispvar( v, name )
switch class( v ),
case 'struct',
fn = fieldnames( v );
if ~isempty( name ), name( end + 1 ) = '.'; end
names = {}; sizes = {};
for k = 1 : length( fn ),
[ name2, size2 ] = dispvar( subsref(v,struct('type','.','subs',fn{k})), [ name, fn{k} ] );
names( end + 1 : end + length( name2 ) ) = name2;
sizes( end + 1 : end + length( size2 ) ) = size2;
if k == 1 && ~isempty( name ), name( 1 : end - 1 ) = ' '; end
end
case 'cell',
names = {}; sizes = {};
for k = 1 : length( v ),
[ name2, size2 ] = dispvar( v{k}, sprintf( '%s{%d}', name, k ) );
names( end + 1 : end + length( name2 ) ) = name2;
sizes( end + 1 : end + length( size2 ) ) = size2;
if k == 1, name( 1 : end ) = ' '; end
end
case 'double',
names = { name };
sizes = { '(constant)' };
otherwise,
names = { name };
sizes = { [ '(', type( v, true ), ')' ] };
end
% Copyright 2005-2016 CVX Research, Inc.
% See the file LICENSE.txt for full copyright information.
% The command 'cvx_where' will show where this file is located.
|
github
|
xiaoxiaojiangshang/Programs-master
|
apply.m
|
.m
|
Programs-master/matlab/cvx/lib/@cvxtuple/apply.m
| 505 |
utf_8
|
f59f25021974462a358e5189ea5415e8
|
function y = apply( func, x )
y = do_apply( func, x.value_ );
function y = do_apply( func, x )
switch class( x ),
case 'struct',
y = cell2struct( do_apply( func, struct2cell( x ) ), fieldnames( x ), 1 );
case 'cell',
y = cellfun( func, x, 'UniformOutput', false );
otherwise,
y = feval( func, x );
end
% Copyright 2005-2016 CVX Research, Inc.
% See the file LICENSE.txt for full copyright information.
% The command 'cvx_where' will show where this file is located.
|
github
|
xiaoxiaojiangshang/Programs-master
|
cvx_setdual.m
|
.m
|
Programs-master/matlab/cvx/lib/@cvxtuple/cvx_setdual.m
| 954 |
utf_8
|
b6deb370985cc299023b091bbba5dfd6
|
function x = setdual( x, y )
x.dual_ = y;
x.value_ = do_setdual( x.value_, y );
function x = do_setdual( x, y )
switch class( x ),
case 'struct',
nx = numel( x );
if nx > 1,
error( 'Dual variables may not be attached to struct arrays.' );
end
f = fieldnames(x);
y(end+1).type = '{}';
for k = 1 : length(f),
y(end).subs = {1,k};
x.(f{k}) = do_setdual( x.(f{k}), y );
end
case 'cell',
y(end+1).type = '{}';
y(end+1).subs = cell(1,ndims(x));
for k = 1 : numel(nx),
[ y(end).subs{:} ] = { 1, k };
x{k} = do_setdual( x{k}, y );
end
case 'cvx',
x = setdual( x, y );
case 'double',
x = setdual( cvx( x ), y );
end
% Copyright 2005-2016 CVX Research, Inc.
% See the file LICENSE.txt for full copyright information.
% The command 'cvx_where' will show where this file is located.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.