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
|
evanrussek/Predictive-Representations-PLOS-CB-2017-master
|
model_Vpunc.m
|
.m
|
Predictive-Representations-PLOS-CB-2017-master/agents/model_Vpunc.m
| 1,399 |
utf_8
|
b18ff9dc9193e5204a26ccfa219f13ab
|
function model = model_Vpunc()
model.init = @modelinit;
model.update = @modelupdate;
model.eval = @modeleval;
model.choose = @modelchoose;
function model = modelinit(model,game, params_in)
if nargin < 3
% parameters
model.param.epsilon = .1;
model.param.alpha = .25;
model.param.discount = .9;
else
model.param = params_in;
end
% structures
n_s = length(game.Rs)+1;
V = zeros(n_s,1);
model.V = V;
% state/action index
model.s = game.current_state;
model.s_prime = 0;
model.a = 0;
model.a_prime = 0;
model.r = 0;
function model = modelupdate(model,game)
% update M
[model.V] = v_update(model.s,model.r,model.s_prime,model);
function a = modelchoose(Qvals,game,epsilon)
%epsilon = .1;
action_prob = zeros(length(Qvals),1);
[maxval, max_a] = max(Qvals);
[bestA] = find(Qvals==maxval);
action_prob(bestA) = (1 - epsilon)/length(bestA);
action_prob = action_prob + epsilon/length(Qvals);
a = find(rand < cumsum(action_prob),1);
if isempty(a)
keyboard
end
function [Q,model] = modeleval(model,game)
next_state = game.nextState(game.current_state,:);
next_state(next_state == 0) = [];
Q = model.V(next_state);
if any(isnan(Q))
keyboard
end
function V = v_update(s,r,s_prime,model)
V = model.V;
V(s) = model.V(s) + model.param.alpha*(r + model.param.discount*model.V(s_prime) - model.V(s));
if any(isnan(V))
keyboard
end
|
github
|
evanrussek/Predictive-Representations-PLOS-CB-2017-master
|
makegame2.m
|
.m
|
Predictive-Representations-PLOS-CB-2017-master/environment functions/makegame2.m
| 4,424 |
utf_8
|
d7cabf9bf1513b3286d220f86592671f
|
function game = makegame2(locations,magnitude,wallloc, startpos)
% setupmo
rows = 10;
cols = 10;
nstates = rows*cols;
nactions = 4;
if nargin < 4
startpos = [8 1];
end
% map y,x positions to number
global yx_to_state
yx_to_state_t = zeros(cols,rows);
for c = 1:cols
yx_to_state_t(c,:) = 1 + (c-1)*rows : rows*c;
end
yx_to_state = yx_to_state_t';
nwallstates = size(wallloc,1);
wallstates = zeros(nwallstates,1);
for i = 1:nwallstates
wallstates(i) = yx_to_state(wallloc(i,1), wallloc(i,2));
end
%
[Rs, Rsa] = makeR(nstates,locations,magnitude);
[T_init, nextstate_init] = makeT(rows,cols,nactions,locations);
% put in barrier
[newT newNextState] = addwall(T_init,nextstate_init, wallloc);
[available_sa, sa_to_nextstate, nextState] = configSA(newNextState,locations);
game.reward_states = [];
for i = 1:size(locations,1)
game.reward_states = [game.reward_states; yx_to_state(locations(i,1), locations(i,2))];
end
game.rows = rows;
game.cols = cols;
game.T = newT;
game.nextState = nextState;
game.wallloc = wallloc;
game.Rs = Rs;
game.Rsa = Rsa;
game.available_sa = available_sa;
game.sa_to_nextstate = sa_to_nextstate;
game.pos = startpos;
game.start_state = yx_to_state(startpos(1),startpos(2));
game.current_state = game.start_state;
game.wallstates = wallstates;
game.locations = locations;
game.magnitude = magnitude;
function [Rs, Rsa] = makeR(nstates,locations,magnitude)
% locations should be number of reward locations X 2 - y then x
% magnitude should be number of reward locations X 1 - each value is size of reward
% R is nstates X 1, - R(i) is reward value for entering state i
global yx_to_state;
nlocations = length(magnitude);
Rs = zeros(nstates + nlocations,1);
nlocations = length(magnitude);
Rsa = zeros(400+nlocations+1,1);
for i = 1:nlocations
state_i = yx_to_state(locations(i,1), locations(i,2));
Rs(state_i) = magnitude(i);
Rsa(400+i) = magnitude(i);
end
function [T , nextstate] = makeT(rows,cols,nactions,locations)
% this function builds (nstatesxnactions) nextstate matrix
% nextstate mtx takes in (state,action) and gives next state
global yx_to_state;
nrewardlocs = size(locations,1);
nstates = rows*cols;
T = zeros(nstates,nactions,nstates);
newstate = zeros(1,nactions);
nextstate = zeros(nstates,nactions);
% want transition matrix
for x = 1:cols
for y = 1:rows
currstate = yx_to_state(y,x);
% position after action 1 (north)
newpos(1,:) = [(y-1) x];
% position after action 2 (south)
newpos(2,:) = [(y+1) x];
% position after action 3 (east)
newpos(3,:) = [y (x + 1)];
% position after action 4 (west)
newpos(4,:) = [y (x - 1)];
newpos(newpos>rows) = rows; newpos(newpos < 1) = 1;
% for each action
for a = 1:4
ns = yx_to_state(newpos(a,1),newpos(a,2));
newstate(a) = ns;
T(currstate,a,ns) = 1;
end
nextstate(currstate,:) = newstate;
end
end
function [newT newNextState] = addwall(oldT,oldNextState, wallloc)
% updates T and newState so that state-action pairs which lead into wall, lead to state
global yx_to_state;
% at states where there is a wall,
nwallstates = size(wallloc,1);
newNextState = oldNextState;
newT = oldT;
for i = 1:nwallstates
wallstate_i = yx_to_state(wallloc(i,1), wallloc(i,2));
% find s-a pairs that lead to that state
[s,a] = ind2sub(size(oldNextState),find(oldNextState == wallstate_i));
for j = 1:length(s)
% switch transition mtx so those states lead to themselves
newNextState(s(j),a(j)) = s(j);
newT(s(j),a(j), wallstate_i) = 0;
newT(s(j),a(j), s(j)) = 1;
end
end
function [available_sa, sa_to_nextstate, nextState] = configSA(nextState,locations)
nlocations = size(locations,1);
nstates = 100+nlocations+1;
% available_sa
available_sa = zeros(nstates,4);
available_sa(1:100,:) = reshape(1:400,[100 4]);
global yx_to_state
for i = 1:nlocations
thisloc = locations(i,:);
this_state = yx_to_state(thisloc(1), thisloc(2));
available_sa(this_state,:) = [400+i, 0, 0, 0];
available_sa(100+i,:) = [400+nlocations+1,0,0,0];
end
% sa_to_nextstate
sa_to_nextstate = zeros(400+nlocations+1,1);
for i = 1:nlocations
thisloc = locations(i,:);
this_state = yx_to_state(thisloc(1), thisloc(2));
nextState(this_state,:) = [100+i, 0 0 0];
nextState = [nextState; nstates, 0 , 0, 0];
end
nextState = [nextState; 0 0 0 0];
for i = 1:400+nlocations+1
[row, col] = find(available_sa == i);
if length(row) == 1
sa_to_nextstate(i) = nextState(row,col);
end
end
|
github
|
proteekroy/U-NSGA-III-master
|
nsga2_selection.m
|
.m
|
U-NSGA-III-master/nsga2_selection.m
| 3,756 |
utf_8
|
fe4f9081b3ddc830d7d2ef6508f14ffb
|
% Copyright [2017] [Proteek Chandan Roy]
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
%This function applies NSGA-II selection for merged population
function opt = nsga2_selection(opt)
[n, ~] = size(opt.totalpopObj);
opt.R = zeros(size(opt.totalpopObj,1),1);
selectedPopIndex = [];
index = opt.totalpopCV<=0;
FeasiblePopIndex = find(index == 1);
InfeasiblePopIndex = find(index == 0);
%---------------Find Non-dominated Sorting of Feasible Solutions-------
R = zeros(n,1);
F = cell(n,1);
opt.R = zeros(n,1);
if ~isempty(FeasiblePopIndex)
[R,~] = bos(opt.totalpopObj(FeasiblePopIndex,:));
for i=1:size(FeasiblePopIndex,1)
F{R(i)} = horzcat(F{R(i)}, FeasiblePopIndex(i));
end
%---------------Store Ranking of Feasible Solutions--------------------
opt.R(FeasiblePopIndex) = R;
end
%--------------Rank the Infeasible Solutions---------------------------
if ~isempty(InfeasiblePopIndex)
CV = opt.totalpopCV(InfeasiblePopIndex);
[~,index] = sort(CV,'ascend');
c = max(R) + 1;
for i = 1: size(index,1)
if i>1 && (CV(index(i))==CV(index(i-1)))%If both CV are same, they are in same front
opt.R(InfeasiblePopIndex(index(i))) = opt.R(InfeasiblePopIndex(index(i-1)));
b = opt.R(InfeasiblePopIndex(index(i)));
F{b} = horzcat(F{b}, InfeasiblePopIndex(index(i)));
else
opt.R(InfeasiblePopIndex(index(i))) = c ;
F{c} = horzcat(F{c}, InfeasiblePopIndex(index(i)));
c = c + 1;
end
end
end
%----------------Select High Rank Solutions----------------------------
count = zeros(n,1);
for i=1:n
count(i) = size(F{i},2);
end
cd = cumsum(count);
p1 = find(opt.N<cd);
lastfront = p1(1);
opt.pop = zeros(size(opt.pop));
for i=1:lastfront-1
selectedPopIndex = horzcat(selectedPopIndex, F{i});
end
%------------CROWDING DISTANCE PART------------------------------------
opt.CD = zeros(size(opt.totalpopObj,1),1);
for i=1:max(R)
front = F{i};
front_cd = crowdingDistance(opt, front, opt.totalpopObj(front,:));
opt.CD(front) = front_cd;
end
if size(selectedPopIndex,2)<opt.N
index = F{lastfront};
CDlastfront = opt.CD(index);
[~,I] = sort(CDlastfront,'descend');
j = 1;
for i = size(selectedPopIndex,2)+1: opt.N
selectedPopIndex = horzcat(selectedPopIndex, index(I(j)));
j = j + 1;
end
end
%---------------Select for Next Generation-----------------------------
opt.pop = opt.totalpop(selectedPopIndex,:);
opt.popObj = opt.totalpopObj(selectedPopIndex,:);
opt.popCV = opt.totalpopCV(selectedPopIndex,:);
opt.popCons = opt.totalpopCons(selectedPopIndex,:);
opt.CD = opt.CD(selectedPopIndex,:);
end
|
github
|
proteekroy/U-NSGA-III-master
|
nsga2_basic_parameters.m
|
.m
|
U-NSGA-III-master/nsga2_basic_parameters.m
| 10,188 |
utf_8
|
a19d12c82ef480ac57e50f22f45f4857
|
% Copyright [2017] [Proteek Chandan Roy]
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
function [opt] = nsga2_basic_parameters(opt)
%-----OPTIMIZATION ALGORITHM PARAMETERS-------------------------------
opt.eta_c = 15;%crossover index
opt.eta_m = 20;%mutation index
opt.G = 200;% Generations
opt.N = 200;%population size in optimization algorithm
opt.pcross = 0.9; % Crossover probability
opt.nrealcross = 0;%number of crossover performed
opt.nrealmut = 0;%number of mutation performed
opt.gen = 1;%starting generation
opt.pop = [];%initial population
opt.popObj = [];
opt.Epsilon = 1e-14;%numerical difference
opt.Inf = 1e14;%maximum value
opt.initpopsize = opt.N;%initial sample size for high fidelity computation
opt.crossoverOption = 1;% 1 = simulated binary crossover
opt.mutationOption = 1;% 1 = polynomial mutation
opt.matingselectionOption = 1;%1 = binary constraint tournament selection
opt.survivalselectionOption = 2;%1 = NSGA-II, 2 = NSGA-III
opt.associationsReady = false;
if opt.survivalselectionOption==1
opt.algorithm_name = 'nsga2';
else
opt.algorithm_name = 'nsga3';
end
opt.testfilename = strcat(opt.algorithm_name, '_', lower(opt.objfunction));
%filename where data will be saved
opt.varfilename = strcat(opt.objfunction,'_var_',num2str(opt.r),'.txt');%save variables
opt.objfilename = strcat(opt.objfunction,'_obj_',num2str(opt.r),'.txt');%save objective
opt.cvfilename = strcat(opt.objfunction,'_cv_',num2str(opt.r),'.txt');%constraint violation
%-----OBJECTIVE FUNCTION PARAMETERS------------------------------------
problem = lower(opt.objfunction);
switch(problem)
case {'zdt1','zdt2','zdt3','zdt4','zdt6'}
opt.M = 2;%number of objectives
opt.V = 30;%;10;%number of variables
opt.C = 0;%number of constraints
opt.utopian = [-0.05, -0.05];%ideal point, may not be used
opt.min_val = [0 0];%minimum value for normalization, may not be used
opt.max_val = [1 1];%maximum objective, may not be used
if strcmp(opt.objfunction,'zdt6')
opt.min_val = [0.25 0];
elseif strcmp(opt.objfunction,'zdt3')
opt.utopian = [-0.05, -1.1];
opt.min_val = [0 -1];
opt.max_val = [1 1];
end
case {'dtlz1', 'dtlz2', 'dtlz3','dtlz4', 'dtlz5', 'dtlz7'}
opt.M = 2;
opt.V = 11;
opt.C = 0;
opt.utopian = (-0.05).*ones(1, opt.M);
opt.min_val = zeros(1, opt.M);
opt.max_val = ones(1, opt.M);
case {'wfg1', 'wfg2', 'wfg3','wfg4', 'wfg5', 'wfg6','wfg7','wfg8','wfg9'}
opt.M = 3;
opt.V = 8;
opt.C = 0;
opt.utopian = (-0.05).*ones(1, opt.M);
opt.min_val = zeros(1, opt.M);
opt.max_val = ones(1, opt.M);
case {'uf1', 'uf2', 'uf3','uf4', 'uf5', 'uf6','uf7','uf8','uf9'}
opt.M = 2;
opt.V = 30;
opt.C = 0;
opt.utopian = (-0.05).*ones(1, opt.M);
opt.min_val = zeros(1, opt.M);
opt.max_val = ones(1, opt.M);
case {'do2dk','do2dk1','deb2dk','deb2dk1'}
opt.M = 2;
opt.V = 30;
opt.C = 0;
opt.utopian = (-0.05).*ones(1, opt.M);
opt.min_val = zeros(1, opt.M);
opt.max_val = ones(1, opt.M);
case {'deb3dk','deb3dk1'}
opt.M = 3;
opt.V = 30;
opt.C = 0;
opt.utopian = [-0.05, -0.05 -0.05];
opt.min_val = [0 0 0];
case {'c2dtlz2','c3dtlz2'}
opt.M = 3;
opt.V = 7;
opt.utopian = [-0.05, -0.05 -0.05];
opt.min_val = [0 0 0];
if strcmp(opt.objfunction,'c2dtlz2')
opt.C = 1;
opt.max_val = [1 1 1];
else
opt.C = 3;
opt.max_val = [2.01 2.01 2.01];
end
case 'bnh'
opt.M = 2;
opt.V = 2;
opt.C = 2;
opt.utopian = [-0.05, -0.05];
opt.min_val = [0 0];
opt.max_val = [140 55];
case 'osy'
opt.M = 2;
opt.V = 6;
opt.C = 6;
opt.utopian = [-300 0];
opt.min_val = [-274 4];
opt.max_val = [-42 76];
case 'srn'
opt.M = 2;
opt.V = 2;
opt.C = 2;
opt.utopian = [0 -300];
opt.min_val = [0 -250];
opt.max_val = [240 0];
case 'tnk'
opt.M = 2;
opt.V = 2;
opt.C = 2;
opt.utopian = [-0.001, -0.001];
opt.min_val = [0 0];
opt.max_val = [1.2 1.2];
case 'water'
opt.M = 5;
opt.V = 3;
opt.C = 7;
opt.utopian = (-0.05).*ones(1, opt.M);
opt.min_val = [0.75 0 0 0 0];
opt.max_val = [0.95 0.9 1.0 1.6 3.2];
case 'carside'
opt.M = 3;
opt.V = 7;
opt.C = 10;
opt.utopian = [24.3180 3.5352 10.5610];
opt.min_val = [24.3680 3.5852 10.6110];
opt.max_val = [42.7620 4.0000 12.5210];
case 'welded'
opt.M = 2;
opt.V = 4;
opt.C = 4;
opt.utopian = [2.3316 -0.0496];
opt.min_val = [2.3816 0.0004];
opt.max_val = [36.4403 0.0157];
otherwise
input('Function definition is not found');
end
%--------LOWER AND UPPER BOUND OF DECISION VARIABLE--------------------
opt.bound = zeros(2,opt.V);
opt.bound(2,:) = ones(1,opt.V);
if(strcmpi(opt.objfunction,'zdt4'))
opt.bound(1,2:end) = opt.bound(1,2:end)+(-5);
opt.bound(2,2:end) = opt.bound(2,2:end)*5;
elseif(strcmpi(opt.objfunction,'UF1') ||strcmpi(opt.objfunction,'UF2') || strcmpi(opt.objfunction,'UF5') || strcmpi(opt.objfunction,'UF6') || strcmpi(opt.objfunction,'UF7'))
opt.bound(1,2:end) = opt.bound(1,2:end)+(-1);
opt.bound(2,2:end) = opt.bound(2,2:end)*1;
elseif(strcmpi(opt.objfunction,'UF4') )
opt.bound(1,2:end) = opt.bound(1,2:end)+(-2);
opt.bound(2,2:end) = opt.bound(2,2:end)*2;
elseif(strcmpi(opt.objfunction,'UF8') || strcmpi(opt.objfunction,'UF9')|| strcmpi(opt.objfunction,'UF10'))
opt.bound(1,3:end) = opt.bound(1,3:end)+(-2);
opt.bound(2,3:end) = opt.bound(2,3:end)*2;
elseif(strcmpi(opt.objfunction,'BNH'))
opt.bound(2,1)=5;
opt.bound(2,2)=3;
elseif(strcmpi(opt.objfunction,'OSY'))
opt.bound(2,1)=10;%x1
opt.bound(2,2)=10;
opt.bound(2,6)=10;
opt.bound(1,3)=1;
opt.bound(1,5)=1;
opt.bound(2,3)=5;
opt.bound(2,5)=5;
opt.bound(2,4)=6;
elseif(strcmpi(opt.objfunction,'SRN'))
opt.bound(1,1:end) = opt.bound(1,1:end)+(-20);
opt.bound(2,1:end) = opt.bound(2,1:end)*20;
elseif(strcmpi(opt.objfunction,'TNK'))
opt.bound(2,1:end) = opt.bound(2,1:end)*pi;
elseif(strcmpi(opt.objfunction,'WATER'))
opt.bound(1,1:end) = opt.bound(1,1:end)+0.01;
opt.bound(2,1) = 0.45;
opt.bound(2,2:end) = 0.10;
elseif(strcmpi(opt.objfunction,'carside'))
opt.bound(1,1:end) = [0.5 0.45 0.5 0.5 0.875 0.4 0.4];
opt.bound(2,1:end) = [1.5 1.35 1.5 1.5 2.625 1.2 1.2];
elseif(strcmpi(opt.objfunction,'welded'))
opt.bound(1,1:end) = [0.125 0.1 0.1 0.125];
opt.bound(2,1:end) = [5 10 10 5];
elseif (strcmpi(opt.objfunction,'wfg1') || strcmpi(opt.objfunction,'wfg2') || strcmpi(opt.objfunction,'wfg3') ...
|| strcmpi(opt.objfunction,'wfg4') || strcmpi(opt.objfunction,'wfg5') || strcmpi(opt.objfunction,'wfg6')...
|| strcmpi(opt.objfunction,'wfg7') || strcmpi(opt.objfunction,'wfg8') || strcmpi(opt.objfunction,'wfg9'))
opt.bound(1,:) = zeros(1,opt.V);
opt.bound(2,:) = ones(1,opt.V);
end
%---------REFERENCE DIRECTION------------------------------------------
%% Haitham - Start
dirCount = inf;
tempN = opt.N;
while dirCount > opt.N
opt.dirs = initweight(opt.M, tempN)';
dirCount = size(opt.dirs, 1);
tempN = tempN - 1;
end
% Haitham - End
% %Three obj
% if opt.M==5
% opt.dirs = initweight(5, 210)';
% elseif opt.M==3 %Three obj
% opt.dirs = initweight(3, 91)';
% else
% opt.dirs = initweight(2, 21)';
% end
%initialization
opt.numdir = size(opt.dirs,1);%number of reference directions
opt.curdir = opt.dirs(1,:);%current direction
opt.pmut = 1.0/opt.V; %Mutation probability
opt.CD = zeros(opt.N,1);%initial crowding distance
opt.PR = zeros(opt.N,1);%initial pagerank for PR
opt.Color = {'k','b','r','g','y',[.5 .6 .7],[.8 .2 .6]}; %Colors.
opt.totalFuncEval = opt.N * opt.G;%total number of function evaluation
end
%------------------------------END OF -FILE--------------------------------
|
github
|
proteekroy/U-NSGA-III-master
|
lhsamp_model.m
|
.m
|
U-NSGA-III-master/lhsamp_model.m
| 684 |
utf_8
|
b7f69e0e86d4ff88a19e401b51ad4f45
|
%LHSAMP Latin hypercube distributed random numbers
%
% Call: S = lhsamp
% S = lhsamp(m)
% S = lhsamp(m, n)
%
% m : number of sample points to generate, if unspecified m = 1
% n : number of dimensions, if unspecified n = m
%
% S : the generated n dimensional m sample points chosen from
% uniform distributions on m subdivions of the interval (0.0, 1.0)
function S = lhsamp_model(init_pop, opt)
m = init_pop;%opt.initpopsize;
n = opt.V;
S = zeros(m,n);
for i = 1 : n
S(:, i) = (rand(1, m) + (randperm(m) - 1))' / m;
end
%generate each point
for i=1:m
S(i,:) = opt.bound(1,:) + (opt.bound(2,:)-opt.bound(1,:)).*S(i,:); %low + difference*rand(0,1)
end
|
github
|
proteekroy/U-NSGA-III-master
|
initweight.m
|
.m
|
U-NSGA-III-master/initweight.m
| 1,058 |
utf_8
|
9514a2706de36304cb8ac18d16ab8e55
|
% This function is written by Dr. Aimin Zhou for generating any number of weight vectors
function W = initweight(objDim, N)
U = floor(N^(1/(objDim-1)))-2;
M = 0;
while M<N
U = U+1;
M = noweight(U, 0, objDim);
end
W = zeros(objDim, M);
C = 0;
V = zeros(objDim, 1);
[W, C] = setweight(W, C, V, U, 0, objDim, objDim);
W = W / (U + 0.0);
pos = (W < 1.0E-5);
W(pos) = 1.0E-5;
end
%%
function M = noweight(unit, sum, dim)
M = 0;
if dim == 1
M = 1;
return;
end
for i = 0 : 1 : (unit - sum)
M = M + noweight(unit, sum + i, dim - 1);
end
end
%%
function [w, c] = setweight(w, c, v, unit, sum, objdim, dim)
if dim == objdim
v = zeros(objdim, 1);
end
if dim == 1
c = c + 1;
v(1) = unit - sum;
w(:, c) = v;
return;
end
for i = 0 : 1 : (unit - sum)
v(dim) = i;
[w, c] = setweight(w, c, v, unit, sum + i, objdim, dim - 1);
end
end
|
github
|
proteekroy/U-NSGA-III-master
|
pol_mut.m
|
.m
|
U-NSGA-III-master/pol_mut.m
| 1,724 |
utf_8
|
f9fb82822294f15a5f9400264f983295
|
% Copyright [2017] [Proteek Chandan Roy]
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
%This file implements polynomial mutation
function [pop_mut, nrealmut] = pol_mut(pop_crossover, pmut, nrealmut, eta_m, Xmin, Xmax )
[N, nreal] = size( pop_crossover); % Population size & Number of variables
pop_mut = pop_crossover;% Child before mutation
for ind = 1:N
for i = 1:nreal
if rand <= pmut
y = pop_mut(ind,i);
yl = Xmin(i);
yu = Xmax(i);
delta1 = (y-yl) / (yu-yl);
delta2 = (yu-y) / (yu-yl);
rand_var = rand;
mut_pow = 1.0/(eta_m+1.0);
if rand_var <= 0.5
xy = 1.0 - delta1;
val = 2.0*rand_var + (1.0 - 2.0*rand_var) * xy^(eta_m+1.0);
deltaq = val^mut_pow - 1.0;
else
xy = 1.0 - delta2;
val = 2.0*(1.0 - rand_var) + 2.0*(rand_var-0.5) * xy^(eta_m+1.0);
deltaq = 1.0 - val^mut_pow;
end
y = y + deltaq*(yu - yl);
if (y<yl), y = yl; end
if (y>yu), y = yu; end
pop_mut(ind,i) = y;
nrealmut = nrealmut+1;
end
end
end
|
github
|
proteekroy/U-NSGA-III-master
|
calculate_feasible_paretofront.m
|
.m
|
U-NSGA-III-master/calculate_feasible_paretofront.m
| 1,223 |
utf_8
|
82de86fb954b015d2d4683c41d21144e
|
% Copyright [2017] [Proteek Chandan Roy]
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
function [FeasibleIndex, ParetoIndex] = calculate_feasible_paretofront(opt, pop, popObj, popCV)
%-------------FIND FEASIBLE PARETO FRONT-------------------------------
if opt.C>0 %Feasible Pareto front of Constraint Problems
index = find(popCV<=0);
else
index = (1:size(pop,1))';
end
FeasibleIndex = index;
if size(index,1)>0 % there are some feasible solutions
index2 = paretoFront(popObj(index,:));
ParetoIndex = index(index2)';
else % no feasible solution yet
ParetoIndex = [];
end
end
|
github
|
proteekroy/U-NSGA-III-master
|
nsga2_main.m
|
.m
|
U-NSGA-III-master/nsga2_main.m
| 3,778 |
utf_8
|
414dd86ff659dd183e990134d31cb0ad
|
% Copyright [2017] [Proteek Chandan Roy]
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
%This is main function that runs NSGA-II procedure
function opt = nsga2_main(opt)
%------------INITIALIZE------------------------------------------------
opt.pop = lhsamp_model(opt.N, opt);%LHS Sampling
%------------EVALUATE--------------------------------------------------
[opt.popObj, opt.popCons] = evaluate_pop(opt, opt.pop);
opt.popCV = evaluateCV(opt.popCons);
opt.archiveObj = opt.popObj;%to save all objectives
opt.archive = opt.pop;
opt.archiveCV = opt.popCV;
%-------------------PLOT INITIAL SOLUTIONS-----------------------------
plot_population(opt, opt.popObj);
if exist(opt.histfilename, 'file')==2
delete(opt.histfilename);
end
%--------------- OPTIMIZATION -----------------------------------------
funcEval = opt.N;
while funcEval < opt.totalFuncEval % Generation # 1 to
M1 = repmat(funcEval, opt.N, 1);
M2 = opt.pop;
M3 = opt.popObj;
M4 = (-1)*opt.popCV;
M = horzcat(M1, M2, M3, M4);
dlmwrite(opt.histfilename, M, '-append', 'delimiter',' ','precision','%.10f');%history of run
opt = mating_selection(opt);%--------Mating Parent Selection-------
opt = crossover(opt);%-------------------Crossover-----------------
opt = mutation(opt);%--------------------Mutation------------------
%---------------EVALUATION-----------------------------------------
[opt.popChildObj, opt.popChildCons] = evaluate_pop(opt, opt.popChild);
opt.popCV = evaluateCV(opt.popCons);
opt.popChildCV = evaluateCV(opt.popChildCons);
%---------------MERGE PARENT AND CHILDREN--------------------------
opt.totalpopObj = vertcat(opt.popChildObj, opt.popObj);
opt.totalpop = vertcat(opt.popChild, opt.pop);
opt.totalpopCV = vertcat(opt.popChildCV, opt.popCV);
opt.totalpopCons = vertcat(opt.popChildCons, opt.popCons);
%-----------------SURVIVAL SELECTION-------------------------------
opt = survival_selection(opt);
funcEval = funcEval + opt.N;
opt.popCV = evaluateCV(opt.popCons);
opt.archive = vertcat(opt.archive,opt.pop);
opt.archiveObj = vertcat(opt.archiveObj,opt.popObj);
opt.archiveCV = vertcat(opt.archiveCV,opt.popCV);
%-------------------PLOT NEW SOLUTIONS-----------------------------
if mod(funcEval,1000)==0
disp(funcEval);
plot_population(opt, opt.popObj);
end
%[opt.FeasibleIndex, opt.ParetoIndex] = calculate_feasible_paretofront(opt, opt.archive, opt.archiveObj, opt.archiveCV);
end
M1 = repmat(funcEval, opt.N, 1);
M2 = opt.pop;
M3 = opt.popObj;
M4 = (-1)*opt.popCV;
M = horzcat(M1, M2, M3, M4);
dlmwrite(opt.histfilename, M, '-append', 'delimiter',' ','precision','%.10f');%history of run
end%end of function
%------------------------------END OF -FILE--------------------------------
|
github
|
proteekroy/U-NSGA-III-master
|
crossover.m
|
.m
|
U-NSGA-III-master/crossover.m
| 1,060 |
utf_8
|
9fd9fdc06007fb5334b3806be4488984
|
% Copyright [2017] [Proteek Chandan Roy]
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
function [opt] = crossover(opt)
switch(opt.crossoverOption)
case 1
[opt.popChild, opt.nrealcross] = sbx(opt.popChild, opt.pcross, opt.nrealcross, opt.eta_c, opt.bound(1,:), opt.bound(2,:), opt.Epsilon);
otherwise
[opt.popChild, opt.nrealcross] = sbx(opt.popChild, opt.pcross, opt.nrealcross, opt.eta_c, opt.bound(1,:), opt.bound(2,:), opt.Epsilon);
end
end
|
github
|
proteekroy/U-NSGA-III-master
|
sbx.m
|
.m
|
U-NSGA-III-master/sbx.m
| 3,387 |
utf_8
|
8016f8a750f4d50f32052960259732d9
|
% Copyright [2017] [Proteek Chandan Roy]
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
function [pop_crossover, nrealcross] = sbx(pop_selection, p_cross, nrealcross, eta_c, Xmin, Xmax, epsilon)
[N, nreal] = size(pop_selection); % Population size & Number of variables
pop_crossover = zeros( size(pop_selection) );%Child population
if mod(N,2) ~= 0 %check if N is odd
pop_crossover(N,:) = pop_selection(randi(N),:);%pick a random element for last solution if N is odd
N = N - 1;
end
p = randperm(N);
for ind=1:2:N
p1 = p(ind);
p2 = p(ind+1);
parent1 = pop_selection(p1,:);
parent2 = pop_selection(p2,:);
child1 = zeros(1, nreal);
child2 = zeros(1, nreal);
if rand <= p_cross
nrealcross = nrealcross+1;
for i=1:nreal
if rand <= 0.5
if abs( parent1(i)-parent2(i) ) > epsilon
if parent1(i) < parent2(i)
y1 = parent1(i);
y2 = parent2(i);
else
y1 = parent2(i);
y2 = parent1(i);
end
yl = Xmin(i);
yu = Xmax(i);
beta = 1.0 + (2.0*(y1-yl)/(y2-y1));
alpha = 2.0 - beta^(-(eta_c+1.0));
rand_var = rand;
if rand_var <= (1.0/alpha)
betaq = (rand_var*alpha)^(1.0/(eta_c+1.0));
else
betaq = (1.0/(2.0 - rand_var*alpha))^(1.0/(eta_c+1.0));
end
c1 = 0.5*((y1+y2) - betaq*(y2-y1));
beta = 1.0 + (2.0*(yu-y2)/(y2-y1));
alpha = 2.0 - beta^(-(eta_c+1.0));
if rand_var <= (1.0/alpha)
betaq = (rand_var*alpha)^(1.0/(eta_c+1.0));
else
betaq = (1.0/(2.0 - rand_var*alpha))^(1.0/(eta_c+1.0));
end
c2 = 0.5*((y1+y2)+betaq*(y2-y1));
if (c1 < yl), c1 = yl; end
if (c2 < yl), c2 = yl; end
if (c1 > yu), c1 = yu; end
if (c2 > yu), c2 = yu; end
if rand <= 0.5
child1(i) = c2;
child2(i) = c1;
else
child1(i) = c1;
child2(i) = c2;
end
else
child1(i) = parent1(i);
child2(i) = parent2(i);
end
else
child1(i) = parent1(i);
child2(i) = parent2(i);
end
end
else
child1 = parent1;
child2 = parent2;
end
pop_crossover(ind,:) = child1;
pop_crossover(ind+1,:) = child2;
end
|
github
|
proteekroy/U-NSGA-III-master
|
mutation.m
|
.m
|
U-NSGA-III-master/mutation.m
| 1,043 |
utf_8
|
e894e51e73b91d9dae7c485dc2ebef95
|
% Copyright [2017] [Proteek Chandan Roy]
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
function [opt] = mutation(opt)
switch(opt.mutationOption)
case 1
[opt.popChild, opt.nrealmut] = pol_mut(opt.popChild, opt.pmut, opt.nrealmut, opt.eta_m, opt.bound(1,:), opt.bound(2,:) );
otherwise
[opt.popChild, opt.nrealmut] = pol_mut(opt.popChild, opt.pmut, opt.nrealmut, opt.eta_m, opt.bound(1,:), opt.bound(2,:) );
end
end
|
github
|
proteekroy/U-NSGA-III-master
|
evaluate_pop.m
|
.m
|
U-NSGA-III-master/evaluate_pop.m
| 1,248 |
utf_8
|
4afe8b4282b9d56b9d1d8076c925da1f
|
% Copyright [2017] [Proteek Chandan Roy]
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
%
% Proteek Chandan Roy, 2016
% Contact: [email protected], [email protected]
%-------------HIGH FIDELITY EVALUATION OF POPULATION-----------------------
function [popObj, popCons] = evaluate_pop(opt, pop)
popObj = zeros(size(pop,1),opt.M);
if opt.C>0
popCons = zeros(size(pop,1),opt.C);
else
popCons = zeros(size(pop,1), 1);
end
sz = size(pop,1);
for i = 1:sz
[f, g] = high_fidelity_evaluation(opt, pop(i,:));
popObj(i, 1:opt.M) = f;
if opt.C>0
popCons(i,:) = g;
else
popCons(i,1) = 0;
end
end
end
|
github
|
proteekroy/U-NSGA-III-master
|
plot_population.m
|
.m
|
U-NSGA-III-master/plot_population.m
| 1,196 |
utf_8
|
0e33d1ac9e0b53bd0f7ad8f3a5ed6700
|
% Copyright [2017] [Proteek Chandan Roy]
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
%This function plots population of each generation with different color
function plot_population(opt, popObj)
figure(opt.fig);
%hold all;
if opt.M==2
plot(popObj(:,1),popObj(:,2),'o','MarkerEdgeColor',opt.Color{randi(size(opt.Color,2))},'MarkerFaceColor',opt.Color{randi(size(opt.Color,2))});
elseif opt.M==3
plot3(popObj(:,1),popObj(:,2),popObj(:,3),'o','MarkerEdgeColor',opt.Color{randi(size(opt.Color,2))},'MarkerFaceColor',opt.Color{randi(size(opt.Color,2))});
end
%xlim([0 1])
%ylim([0 2])
drawnow;
end
|
github
|
proteekroy/U-NSGA-III-master
|
constrained_tournament_selection.m
|
.m
|
U-NSGA-III-master/constrained_tournament_selection.m
| 3,148 |
utf_8
|
4432c055ad3ad0ec66c819e1963c8ee4
|
% Copyright [2017] [Proteek Chandan Roy]
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
% This file picks solution from tournament with this logic-
% If both are feasible pick a) Pick the one which has lower (better) rank
% b) Or If both are in same rank then pick the one with less crowding
% distance
% If one of them is feasible, pick the feasible one
% If both are infeasible, then pick the one with less constraint violation
% If CV values are same, then pick randomly
function selected_pop = constrained_tournament_selection(opt, pop, popObj, popCV)
N = opt.N;% pop size
%----TOURNAMENT CANDIDATES-------------------------------------------------
tour1 = randperm(N);
tour2 = randperm(N);
%----START TOURNAMENT SELECTION--------------------------------------------
selected_pop = zeros(N, opt.V); % Only the design variables of the selected members
for i = 1:N
p1 = tour1(i);
p2 = tour2(i);
if (popCV(p1)<=0 && popCV(p2)<=0)%both are feasible
obj1 = popObj(p1,:);
obj2 = popObj(p2,:);
d = lex_dominate(obj1, obj2);
if d == 1 %p1 dominates p2
selected_pop(i, :) = pop(p1,1:opt.V);
elseif d == 3 % p2 dominates p1
selected_pop(i, :) = pop(p2,1:opt.V);
else % d == 2
% check crowding distance
if(opt.CD(p1)>opt.CD(p2))
selected_pop(i, :) = pop(p1,1:opt.V);
elseif (opt.CD(p1)<opt.CD(p2))
selected_pop(i, :) = pop(p2,1:opt.V);
else %randomly pick any solution
if(rand <= 0.5)
pick = p1;
else
pick = p2;
end
selected_pop(i, :) = pop(pick,1:opt.V);
end
end
else
if(popCV(p1) < popCV(p2)) %p1 less constraint violation
selected_pop(i, :) = pop(p1,1:opt.V);
else
if (popCV(p2) < popCV(p1))
selected_pop(i, :) = pop(p2,1:opt.V); %p2 has less constraint violation
else %randomly pick any solution
if(rand <= 0.5)
pick = p1;
else
pick = p2;
end
selected_pop(i, :) = pop(pick,1:opt.V);%initially p1 was randomly choosen
end
end
end
end
end
|
github
|
proteekroy/U-NSGA-III-master
|
bos.m
|
.m
|
U-NSGA-III-master/bos.m
| 3,896 |
utf_8
|
09bb3c8d6145d4e68512b7d21eea72b4
|
% Copyright [2017] [Proteek Chandan Roy]
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
% This file implemented non-dominated sorting algorithm of the following paper
% "Best Order Sort: A New Algorithm to Non-dominated Sorting for Evolutionary Multi-objective Optimization"
% - Proteek Chandan Roy, Md. Monirul Islam and Kalyanmoy Deb, Michigan State University, East Lansing, MI, USA
% https://github.com/Proteek/Best-Order-Sort
% This software is protected under Apache License 2.0 which can be found in http://www.apache.org/licenses/LICENSE-2.0.txt
% @author Proteek Chandan Roy, Department of CSE, Michigan State University, USA
function [R,F] = bos(objective)
if isempty(objective)
R = [];
F = [];
return;
elseif size(objective,1)==1
R = 1;
F(1).f = 1;
return;
end
%--------INITIALIZATION---------------
[n,m]= size(objective);
R = ones(n,1);
if(m<4)
m1 = m;
else
m1 = floor(min(ceil(log2(n)),m));
end
%---------SORTING PART-----------------
Q = zeros(n, m1);
lex_order = zeros(n,1);
%--------FIND LEX ORDER----------------
[~,Q(:,1)] = sortrows(objective);
for i = 1:n
lex_order(Q(i,1)) = i;
end
for i = 2:m1
%H = horzcat(objective(:,i), lex_order);%in case of tie use lex order
H = horzcat(objective(:,i), objective(:,1));
[~,Q(:,i)] = sortrows(H);
end
%-------RANKING PART-------------------
done = zeros(n, 1);
total = 0;
totalfront = 1;
L = cell(m1, n);
for i = 1:n
for j = 1:m1
s = Q(i,j);
if done(s) == 1
L{j, R(s)} = horzcat(s, L{j, R(s)});
continue;
end
total = total + 1;
done(s) = 1;
for k = 1: totalfront %for all front
d = 0;
sz = size(L{j,k},2);
for l = 1:sz % for all elements
d = lex_dominate(objective(L{j,k}(l),:), objective(s,:));
if d == 1
break;
end
end
if d == 0 %not dominates
R(s) = k;
L{j, k} = horzcat(s, L{j, k});
break;
elseif d==1 && k==totalfront
totalfront = totalfront + 1;
R(s) = totalfront;
L{j,totalfront} = horzcat(s, L{j,totalfront});
break;
end
end
if total==n
break;
end
end
end
F(n).f = [];
for i=1:n
F(R(i)).f = [F(R(i)).f i];
end
end
%checks lexicographical domination of two solutions
function [d] = lex_dominate(obj1, obj2)
equal = 1;
d = 1;
sz = size(obj1,2);
for i = 1:sz
if obj1(i) > obj2(i)
d = 0;
break;
elseif(equal==1 && obj1(i) < obj2(i))
equal = 0;
end
end
if d ==1 && equal==1 %check if both solutions are equal
d = 0;
end
end
|
github
|
proteekroy/U-NSGA-III-master
|
survival_selection.m
|
.m
|
U-NSGA-III-master/survival_selection.m
| 1,103 |
utf_8
|
b2bd1a5c58c1263c4a65376474f0107f
|
% Copyright [2017] [Proteek Chandan Roy]
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
function [opt] = survival_selection(opt)
switch(opt.survivalselectionOption)
case 1 %------------------NSGA-II----------------------------------
opt = nsga2_selection(opt);
case 2 %------------------NSGA-III----------------------------------
opt = nsga3_selection(opt);
otherwise
disp('Survival Selection is not defined');
end
end
|
github
|
proteekroy/U-NSGA-III-master
|
crowdingDistance.m
|
.m
|
U-NSGA-III-master/crowdingDistance.m
| 1,529 |
utf_8
|
d5106f814202596463a1dd74f6fb2050
|
% Copyright [2017] [Proteek Chandan Roy]
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
%This function calculates crowding distance for front-f
function [CDF] = crowdingDistance(opt, f, objective)
if size(f,2)==1
CDF = opt.Inf;
elseif size(f,2)==2
CDF(1) = opt.Inf;
CDF(2) = opt.Inf;
else
[M1, I1] = min(objective);
[M2, I2] = max(objective);
I = horzcat(I1, I2);
I = unique(I);
CDF = zeros(size(f,2),1);
for i = 1:size(objective,2)
[~,index] = sort(objective(:,i));
for j = 2:size(index,1)-1
if (abs(M2(i)-M1(i)) > opt.Epsilon)
CDF(index(j)) = CDF(index(j))+ ((objective(index(j+1),i)-objective(index(j-1),i))/(M2(i)-M1(i))) ;
end
end
end
CDF(2:end-1) = CDF(2:end-1)/ size(objective,2);
CDF(I) = opt.Inf;
end
end
|
github
|
proteekroy/U-NSGA-III-master
|
lex_dominate.m
|
.m
|
U-NSGA-III-master/lex_dominate.m
| 1,117 |
utf_8
|
0ba44dfca024e0f3638f1de3cd8ae8d9
|
% Copyright [2017] [Proteek Chandan Roy]
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
function [d] = lex_dominate(obj1, obj2)
a_dom_b = 0;
b_dom_a = 0;
sz = size(obj1,2);
for i = 1:sz
if obj1(i) > obj2(i)
b_dom_a = 1;
elseif(obj1(i) < obj2(i))
a_dom_b = 1;
end
end
if(a_dom_b==0 && b_dom_a==0)
d = 2;
elseif(a_dom_b==1 && b_dom_a==1)
d = 2;
else
if a_dom_b==1
d = 1;
else
d = 3;
end
end
end
|
github
|
proteekroy/U-NSGA-III-master
|
main.m
|
.m
|
U-NSGA-III-master/main.m
| 4,137 |
utf_8
|
d9abd04e8d176117a44808f970124307
|
% Copyright [2017] [Proteek Chandan Roy]
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
% This Software runs NSGA-II procedure for different testfunctions
% You are free to change, modify, share and distribute this software
% Please Acknowledge the author (if possible) for any use of this software
% @author Proteek Chandan Roy, Department of CSE, Michigan State University, USA
% email: [email protected]
function main()
test_function = ['zdt1 ';'zdt2 ';'zdt3 ';'zdt4 ';'zdt6 ';...
'dtlz1 ';'dtlz2 ';'dtlz3 ';'dtlz4 '; 'dtlz5 ';...
'dtlz7 ';'srn ';'bnh ';'osy ';'tnk ';...
'c2dtlz2'; 'DO2DK ';'DO2DK1 '; 'DEB2DK ';'DEB2DK1';...
'DEB3DK ';'DEB3DK1' ;'UF1 '];
%-------------------MAIN LOOP----------------------------------------------
run = 1;%number of runs
for func_no = 16:1:16%:4%for all test functions
for r = 1:1:run%number of runs
opt.r = r;%run number
disp(r);
opt.objfunction = strtrim(test_function(func_no,:));%remove whitespaces
%opt.func_no = func_no;%function number
opt = nsga2_basic_parameters(opt);%basic parameters of evolutionary algorithm
opt.pareto = load('Pareto Front/C2DTLZ2.3D.pf');%Pareto front
%-----------PLOT PARETO FRONT----------------------------------
opt.fig = figure;
plot_population(opt, opt.pareto);
if r<10
opt.objfilename = strcat(opt.testfilename,'_00',num2str(r),'.obj');
opt.histfilename = strcat(opt.testfilename,'_00',num2str(r),'.hist');
elseif r<100
opt.objfilename = strcat(opt.testfilename,'_0',num2str(r),'.obj');
opt.histfilename = strcat(opt.testfilename,'_0',num2str(r),'.hist');
else
opt.objfilename = strcat(opt.testfilename,'_',num2str(r),'.obj');
opt.histfilename = strcat(opt.testfilename,'_',num2str(r),'.hist');
end
%---------------- OPTIMIZE ------------------------------------
opt = nsga2_main(opt);
%----------------WRITE TO FILE---------------------------------
[~, ParetoIndex] = calculate_feasible_paretofront(opt, opt.pop, opt.popObj, opt.popCV);
dlmwrite(opt.objfilename, opt.popObj(ParetoIndex,:), 'delimiter',' ','precision','%.10f');%feasible non-dominated front
% dlmwrite(opt.varfilename, opt.pop, 'delimiter',' ','precision','%.10f');%'-apend' for apending
% dlmwrite(opt.objfilename, opt.popObj, 'delimiter',' ','precision','%.10f');
% dlmwrite(opt.cvfilename, opt.popCV, 'delimiter', ' ','precision','%.10f');
% all_filename = strcat('all_fitness',num2str(r),'_nsga2.txt');
% dlmwrite(all_filename, opt.archiveObj, 'delimiter',' ','precision','%.10f');
%----------PLOT PARETO FRONT AND FINAL SOLUTION----------------
opt.fig = figure;
hold all;
plot_population(opt, opt.pareto);
plot_population(opt, opt.popObj);
end
disp('END');
end
end
%------------------------------END OF -FILE--------------------------------
|
github
|
proteekroy/U-NSGA-III-master
|
evaluateCV.m
|
.m
|
U-NSGA-III-master/evaluateCV.m
| 964 |
utf_8
|
aba733d42645f2a8e801d363d3ce42e7
|
% Copyright [2017] [Proteek Chandan Roy]
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
%This function evaluates constrain violation (positive if violated), zero
%otherwise
function cv = evaluateCV(pop_cons)
g = pop_cons;
for i=1:size(pop_cons,1)
for j=1:size(pop_cons,2)
if g(i,j)<0
g(i, j) = 0;
end
end
end
cv = sum(g, 2);
end
|
github
|
proteekroy/U-NSGA-III-master
|
mating_selection.m
|
.m
|
U-NSGA-III-master/mating_selection.m
| 1,062 |
utf_8
|
9656a0552b11d50596840660516c1ffe
|
% Copyright [2017] [Proteek Chandan Roy]
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
function [opt] = mating_selection(opt)
switch(opt.survivalselectionOption)
case 1
opt.popChild = constrained_tournament_selection(opt, opt.pop, opt.popObj, opt.popCV);
case 2
opt.popChild = niching_based_tournament_selection(opt, opt.pop, opt.popObj, opt.popCV);
otherwise
opt.popChild = constrained_tournament_selection(opt, opt.pop, opt.popObj, opt.popCV);
end
end
|
github
|
proteekroy/U-NSGA-III-master
|
niching_based_tournament_selection.m
|
.m
|
U-NSGA-III-master/niching_based_tournament_selection.m
| 3,260 |
utf_8
|
96a57b89444c96de933fc0d85a2f884f
|
% Copyright [2017] [Proteek Chandan Roy]
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
% This file picks solution from tournament with this logic-
% If both are feasible pick a) Pick the one which has lower (better) rank
% b) Or If both are in same rank then pick the one with less crowding
% distance
% If one of them is feasible, pick the feasible one
% If both are infeasible, then pick the one with less constraint violation
% If CV values are same, then pick randomly
function selected_pop = niching_based_tournament_selection(opt, pop, popObj, popCV)
N = opt.N;% pop size
%----TOURNAMENT CANDIDATES-------------------------------------------------
tour1 = randperm(N);
tour2 = randperm(N);
%----START TOURNAMENT SELECTION--------------------------------------------
selected_pop = zeros(N, opt.V); % Only the design variables of the selected members
for i = 1:N
p1 = tour1(i);
p2 = tour2(i);
if (popCV(p1)<=0 && popCV(p2)<=0)%both are feasible
if opt.associationsReady && opt.pop2Dir(p1) == opt.pop2Dir(p2)
obj1 = popObj(p1,:);
obj2 = popObj(p2,:);
d = lex_dominate(obj1, obj2);
if d == 1 %p1 dominates p2
selected_pop(i, :) = pop(p1, 1:opt.V);
elseif d == 3 % p2 dominates p1
selected_pop(i, :) = pop(p2, 1:opt.V);
else % d == 2
if opt.pop2DirDistances(p1) < opt.pop2DirDistances(p2)
pick = p1;
else
pick = p2;
end
selected_pop(i, :) = pop(pick,1:opt.V);
end
else
if(rand <= 0.5)
pick = p1;
else
pick = p2;
end
selected_pop(i, :) = pop(pick,1:opt.V); %initially p1 was randomly choosen
end
else
if(popCV(p1) < popCV(p2)) %p1 less constraint violation
selected_pop(i, :) = pop(p1,1:opt.V);
else
if (popCV(p2) < popCV(p1))
selected_pop(i, :) = pop(p2,1:opt.V); %p2 has less constraint violation
else %randomly pick any solution
if(rand <= 0.5)
pick = p1;
else
pick = p2;
end
selected_pop(i, :) = pop(pick,1:opt.V);%initially p1 was randomly choosen
end
end
end
end
end
|
github
|
proteekroy/U-NSGA-III-master
|
high_fidelity_evaluation.m
|
.m
|
U-NSGA-III-master/high_fidelity_evaluation.m
| 14,903 |
utf_8
|
d1a6cd89d5aad2c6b492dc30ae0ac295
|
% Copyright [2017] [Proteek Chandan Roy]
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
%
% Proteek Chandan Roy, 2017
% Contact: [email protected], [email protected]
function [f,g] = high_fidelity_evaluation(opt,x)
problem = lower(opt.objfunction);
g = [];
switch(problem)
case 'zdt1'
n=size(x,2);
a(1)=x(1);
b=9/(n-1);
y=0;
for i=2:n
y=y+x(i);
end
b=b*y;
a(2)=1+b;
a(3)=1- sqrt(a(1)/a(2));
f(1)=a(1);
f(2)=a(2)*a(3);
case 'zdt2'
n=size(x,2);
a(1)=x(1);
b=9/(n-1);
y=0;
for i=2:n
y=y+x(i);
end
b=b*y;
a(2)=1+b;
a(3)=1- power(a(1)/a(2),2);
f(1)=a(1);
f(2)=a(2)*a(3);
case 'zdt3'
n=size(x,2);
a(1)=x(1);
b=9/(n-1);
y=0;
for i=2:n
y=y+x(i);
end
b=b*y;
a(2)=1+b;
a(3)=1- sqrt(a(1)/a(2)) - (a(1)/a(2))*sin(10*pi*a(1));
f(1)=a(1);
f(2)=a(2)*a(3);
case 'zdt4'
n=size(x,2);
a(1)=x(1);
y=0;
for i=2:n
y=y+power(x(i),2)-10*cos(4*pi*x(i));
end
a(2)=1+10*(n-1)+y;
a(3)=1- sqrt(a(1)/a(2));
f(1)=a(1);
f(2)=a(2)*a(3);
case 'zdt6'
n=size(x,2);
a(1)=1- exp(-4*x(1))*power(sin(6*pi*x(1)),6);
y=0;
for i=2:n
y=y+x(i)/9;
end
b=9*power(y,0.25);
a(2)=1+b;
a(3)=1- power(a(1)/a(2),2);
f(1)=a(1);
f(2)=a(2)*a(3);
case 'dtlz1'
n=size(x,2);
g = 0;
nfunc = opt.M;
k = n - nfunc + 1;
for i = nfunc:n
g = g + power(( x(i)-0.5),2) - cos(20 * 3.141592654 * ( x(i)-0.5));
end
g = 100 * (k + g);
for i = 1:nfunc
fit = 0.5 * (1 + g);
for j = nfunc - i:-1:1
fit = fit * x(j);
end
if i > 1
fit = fit * (1 - x(nfunc - i + 1));
end
f(i) = fit;
end
case 'c1dtlz1'
n=size(x,2);
g = 0;
nfunc = opt.M;
k = n - nfunc + 1;
for i = nfunc:n
g = g + power(( x(i)-0.5),2) - cos(20 * 3.141592654 * ( x(i)-0.5));
end
g = 100 * (k + g);
for i = 1:nfunc
fit = 0.5 * (1 + g);
for j = nfunc - i:-1:1
fit = fit * x(j);
end
if i > 1
fit = fit * (1 - x(nfunc - i + 1));
end
f(i) = fit;
end
%now calculate constraints
c = 1.0 - f(nfunc) / 0.6;
for i = 1: nfunc-1
c = c - f(i) / 0.5;
end
g = [];
if(c>=0)
g(1) = 0;
else
g(1) = c;
end
g(1) = -g(1);
case 'dtlz2'
n=size(x,2);
nfunc = opt.M;
k = n - nfunc + 1;
g = 0;
for i = nfunc:n
g = g + power( x(i)-0.5,2);
end
f = zeros(1,nfunc);
for i = 1:nfunc
h = 1 + g;
for j=1:nfunc - i
h =h * cos( x(j) * 3.141592654 / 2);
end
if (i > 1)
h = h*sin( x((nfunc - i + 1)) * 3.141592654 / 2);
end
f(i) = h;
end
case 'c2dtlz2'
n=size(x,2);
nfunc = opt.M;
k = n - nfunc + 1;
g = 0;
for i = nfunc:n
g = g + power( x(i)-0.5,2);
end
fit = zeros(1,nfunc);
for i = 1:nfunc
h = 1 + g;
for j=1:nfunc - i
h =h * cos( x(j) * 3.141592654 / 2);
end
if (i > 1)
h = h*sin( x((nfunc - i + 1)) * 3.141592654 / 2);
end
fit(i) = h;
end
f(1) = fit(1);
f(2) = fit(2);
f(3) = fit(3);
%now calculate constraints
if(nfunc>3)
r = 0.5;
else
r = 0.4;
end
v1 = realmax;
v2 = 0.0;
for i = 1: nfunc
sum1 = power(f(i)-1.0, 2.0);
for j = 1: nfunc
if i ~= j
sum1 = sum1 + power(f(j), 2.0);
end
end
v1 = min(v1, sum1 - power(r, 2.0));
v2 = v2 + power(f(i) - (1.0 / sqrt(nfunc)), 2.0);
end
c = min(v1, v2 - power(r, 2.0));
g = [];
if(c<=0)
g(1) = c;
else
g(1) = c;
end
case 'c3dtlz2'
n = length(x);
xg=x(3:n);
gx=sum((xg-0.5).^2);
f(1)=(1+gx)*cos(x(1)*0.5*pi)*cos(x(2)*0.5*pi);
f(2)=(1+gx)*cos(x(1)*0.5*pi)*sin(x(2)*0.5*pi);
f(3)=(1+gx)*sin(x(1)*0.5*pi);
g(1) = f(1)^2/4 + f(2)^2 + f(3)^2 - 1;
g(2) = f(2)^2/4 + f(1)^2 + f(3)^2 - 1;
g(3) = f(3)^2/4 + f(1)^2 + f(2)^2 - 1;
case 'dtlz3'
x = x';
k = 10;
M = opt.M;
% Error check: the number of dimensions must be M-1+k
n = opt.V;%(M-1) + k; %this is the default
if size(x,1) ~= n
error(['Using k = 10, it is required that the number of dimensions be'...
' n = (M - 1) + k = %d in this case.'], n)
end
xm = x(n-k+1:end,:); %xm contains the last k variables
g = 100*(k + sum((xm - 0.5).^2 - cos(20*pi*(xm - 0.5)),1));
% Computes the functions
f(1,:) = (1 + g).*prod(cos(pi/2*x(1:M-1,:)),1);
for ii = 2:M-1
f(ii,:) = (1 + g) .* prod(cos(pi/2*x(1:M-ii,:)),1) .* ...
sin(pi/2*x(M-ii+1,:));
end
f(M,:) = (1 + g).*sin(pi/2*x(1,:));
case 'dtlz4'
n=size(x,2);
nfunc = opt.M;
k = n - nfunc + 1;
g = 0;
alpha = 100;
for i = nfunc:n
g = g + power( x(i)-0.5,2);
end
f = zeros(1,nfunc);
for i = 1:nfunc
h = 1 + g;
for j=1:nfunc - i
h = h * cos(power( x(j),alpha) * 3.141592654 / 2);
end
if (i > 1)
h = h*sin(power( x((nfunc - i + 1)),alpha) * 3.141592654 / 2);
end
f(i) = h;
end
case 'dtlz5'
n=size(x,2);
nfunc = opt.M;
g = 0;
k = n - nfunc + 1;
for i = nfunc:n
g = g + power( x(i)-0.5,2);
end
t = 3.141592654 / (4 * (1 + g));
theta=[];
theta(1) = x(1) * 3.141592654 / 2;
for i = 2: nfunc - 1
theta(i) = t * (1 + 2 * g * x(i));
end
f = [];
for i = 1:nfunc
h = 1 + g;
for j=1:nfunc - i
h =h * cos(theta(j));
end
if (i > 1)
h = h*sin(theta((nfunc - i + 1)));
end
f(i) = h;
end
case 'dtlz7'
n=size(x,2);
nfunc = opt.M;
k = n - nfunc + 1;
g = sum(x(nfunc:n));
g = 1 + 9 * g / k;
for i = 1:nfunc-1
f(i)=x(i);
end
h2=0;
for j = 1:nfunc-1
h2 =h2 + x(j) / (1 + g) * (1 + sin(3 * 3.141592654 * x(j)));
end
h2 = nfunc - h2;
f(nfunc) = (1 + g) * h2;
case 'bnh'
f(1) = 4*x(1)^2+4*x(2)^2;
f(2) = (x(1)-5)^2+(x(2)-5)^2;
g(1) = (1/25)*((x(1)-5)^2 + x(2)^2-25);
g(2) = -1/7.7*((x(1)-8)^2 + (x(2)+3)^2-7.7);
case 'osy'
f(1) = -(25*(x(1)-2)^2+(x(2)-2)^2+(x(3)-1)^2+(x(4)-4)^2+(x(5)-1)^2);
f(2) = x(1)^2+x(2)^2+x(3)^2+x(4)^2+x(5)^2+x(6)^2;
g(1) = (-1/2)*(x(1)+x(2)-2);
g(2) = (-1/6)*(6-x(1)-x(2));
g(3) = (-1/2)*(2-x(2)+x(1));
g(4) = (-1/2)*(2-x(1)+3*x(2));
g(5) = (-1/4)*(4-(x(3)-3)^2 -x(4));
g(6) = (-1/4)*((x(5)-3)^2+x(6)-4);
case 'srn'
f(1) = 2.0+(x(1)-2.0)^2+(x(2)-1.0)^2;
f(2) = 9.0*x(1)-(x(2)-1)^2;
g(1) = (1/225)*(x(1)^2+x(2)^2-225.0);
g(2) = 0.1*(x(1)-3.0*x(2)+10.0);
case 'tnk'
f(1) = x(1);
f(2) = x(2);
g(1) = (-1)*(x(1)^2+x(2)^2-1.0-0.1*cos(16*atan(x(1)/x(2))));
g(2) = (1/0.5)*((x(1)-0.5)^2+(x(2)-0.5)^2-0.5);
case 'water'
f(1) = (106780.37 * (x(2) + x(3)) + 61704.67)/(8 * power(10, 4));
f(2) = (3000.0 * x(1))/1500;
f(3) = ((305700 * 2289*x(2))/power(0.06 * 2289.0,0.65))/(3 * power(10, 6));
f(4) = (250.0 * 2289.0 * exp(-39.75*x(2) + 9.9*x(3) + 2.74))/(6*power(10, 6));
f(5) = (25.0*((1.39/(x(1)*x(2))) + 4940.0*x(3) - 80.0))/8000;
g(1) = (0.00139/(x(1)*x(2)) + 4.94*x(3) - 0.08 - 1)/13.314;
g(2) = (0.000306/(x(1)*x(2)) + 1.082*x(3) - 0.0986 - 1)/2.0696;
g(3) = (12.307/(x(1)*x(2)) + 49408.24*x(3) + 4051.02 - 50000)/82061.844;
g(4) = (2.098/(x(1)*x(2)) + 8046.33*x(3) - 696.71 - 16000)/5087.923;
g(5) = (2.138/(x(1)*x(2)) + 7883.39*x(3) - 705.04 - 10000)/11463.299;
g(6) = (0.417*(x(1)*x(2)) + 1721.26*x(3) - 136.54 - 2000)/1.0; %this is always feasible
g(7) = (0.164/(x(1)*x(2)) + 631.13*x(3) - 54.48 - 550)/1098.633;
case 'carside'
g(1) = 1.16 - 0.3717 *x(2)*x(4)- 0.0092928 *x(3);
g(2) = 0.261 - 0.0159 * x(1) *x(2)- 0.188 *x(1)* 0.345 - 0.019 *x(2)*x(7) + 0.0144*x(3)*x(5)+ 0.08045 *x(6)* 0.192;
g(3) = 0.214 + 0.00817 *x(5)- 0.131 * x(1) * 0.345 - 0.0704 * x(1) * 0.192 + 0.03099*x(2)*x(6)- 0.018 *x(2)*x(7)+ 0.0208 *x(3)* 0.345 + 0.121 *x(3)* 0.192 - 0.00364*x(5)*x(6)- 0.018 *x(2)^2;
g(4) = 0.74 - 0.61 *x(2) - 0.031296 *x(3)- 0.166 *x(7)* 0.192 + 0.227 *x(2)^2;
g(5) = 28.98 + 3.818 *x(3)- 4.2 * x(1)*x(2)+ 6.63 *x(6)* 0.192 - 7.77 *x(7)* 0.345;
g(6) = 33.86 + 2.95 *x(3)- 5.057 * x(1) *x(2)- 11 *x(2)* 0.345 - 9.98 *x(7)* 0.345 +22 * 0.345 * 0.192;
g(7) = 46.36 - 9.9 *x(2)- 12.9 * x(1) * 0.345;
g(8) = 4.72 - 0.5 *x(4)- 0.19 *x(2)*x(3);
g(9) = 10.58 - 0.674 * x(1)*x(2)- 1.95 *x(2)* 0.345;
g(10) = 16.45 - 0.489 *x(3)*x(7)- 0.843 *x(5)*x(6);
f(1) = 1.98 + 4.9 *x(1)+ 6.67 *x(2)+ 6.98 *x(3)+ 4.01 *x(4) + 1.78 *x(5)+ 0.00001*x(6)+ 2.73 *x(7);
f(2) = g(8);
f(3) = (g(9) + g(10)) / 2.0;
g(1)=- 1 + g(1) / 1.0;
g(2)= -1 + g(2) / 0.32;
g(3)= -1 + g(3) / 0.32;
g(4)= -1 + g(4) / 0.32;
g(5)= -1 + g(5) / 32.0;
g(6)= -1 +g(6)/ 32.0;
g(7)= -1 + g(7)/ 32.0;
g(8)= -1 + g(8)/ 4.0;
g(9)= -1 + g(9)/ 9.9;
g(10)= -1 + g(10)/ 15.7;
case 'welded'
f(1) = 1.10471*x(1)^2*x(2)+0.04811*x(3)*x(4)*(14.0+x(2));
f(2) = 2.1952/(x(4)*x(3)^3);
P = 6000; L = 14; t_max = 13600; s_max = 30000;
R = sqrt(0.25*(x(2)^2+(x(1)+x(3))^2));
M = P*(L+x(2)/2);
J = 2*sqrt(0.5)*x(1)*x(2)*(x(2)^2/12 +0.25*(x(1)+x(3))^2);
t1 = P/(sqrt(2)*x(1)*x(2));
t2 = M*R/J;
t = sqrt(t1^2+t2^2+t1*t2*x(2)/R);
s = 6*P*L/(x(4)*x(3)^2);
P_c = 64746.022*(1-0.0282346*x(3))* x(3)*x(4)^3;
% Constraints
g(1) = (1/t_max)*(t - t_max);
g(2) = (1/s_max)*(s - s_max);
g(3) = (1/(5-0.125))*(x(1)-x(4));
g(4) = (1/P)*(P-P_c);
case 'do2dk'
f = do2dk(x, opt.num_Knee, opt.knee_s);
case 'do2dk1'
f = do2dk1(x, opt.num_Knee, opt.knee_s);
case 'deb2dk'
f = deb2dk(x, opt.num_Knee);
case 'deb2dk1'
f = deb2dk1(x, opt.num_Knee);
case 'deb3dk'
f = deb3dk(x, opt.num_Knee);
case 'deb3dk1'
f = deb3dk1(x, opt.num_Knee);
case 'uf1'
f = UF1(x')';
case 'uf2'
f = UF2(x')';
case 'uf3'
f = UF3(x')';
case 'uf4'
f = UF4(x')';
case 'uf5'
f = UF5(x')';
case 'uf6'
f = UF6(x')';
case 'uf7'
f = UF7(x')';
case 'uf8'
f = UF8(x')';
case 'uf9'
f = UF9(x')';
otherwise
input('Function defition is not found inside high fidelity evaluation');
end
%for unconstraint problem
if opt.C==0
g = [];
end
end
|
github
|
mehr-een/bemkl-rbps-master
|
civalue.m
|
.m
|
bemkl-rbps-master/BEMKL/civalue.m
| 698 |
utf_8
|
0948ed66c5f328a35546256d21c9b141
|
%Mehreen Ali
%[email protected]
function CIndex2 = civalue(y,yhat)
ci = zeros(1,size(y,2));
for k= 1:size(y,2) % col
s = 0; % score sum
n = 0; % eligible pair of scores
for i= 1:size(y,1) % row
for j= i+1:size(y,1) % next row
if (i < j)
if(y(i,k) > y(j,k))
s = s + (yhat(i,k) > yhat(j,k)) + 0.5 * (yhat(i,k) == yhat(j,k));
n = n + 1;
elseif (y(i,k) < y(j,k))
s = s + (yhat(i,k) < yhat(j,k)) + 0.5 * (yhat(i,k) == yhat(j,k));
n = n + 1;
end
end
end
end
ci(k) = s / n;
end
CIndex2 = nanmean(ci);
|
github
|
mehr-een/bemkl-rbps-master
|
bemkl_loocv.m
|
.m
|
bemkl-rbps-master/BEMKL/bemkl_loocv.m
| 5,706 |
utf_8
|
04d503f48a3052ac41dba55272940d1c
|
%Mehreen Ali
%[email protected]
function [validation_response_CV,predicted_response_CV] = bemkl_loocv(drug_source, view_index)
load 'DataViews.mat';
load 'ViewCombinations.mat'; % combos with mut_data
%%%% selected views
view_names = view_combinations{view_index,1};
view_kernels = view_combinations{view_index,2};
index_k = 1:1:58;
num_drugs = size(drug_source,2);
predicted_response_CV=zeros(58, num_drugs);
P = length(view_names);
standardize_response = 0; %0:false 1:true
%%%% LOO-CV
for k = 1:58
learning_indices = find(index_k ~= k);
prediction_indices = k;
Nlearning = length(learning_indices);
Nprediction = length(prediction_indices);
%%%% views dimensions
learning.X = cell(1, P);
prediction.X = cell(1, P);
for m = 1:P
learning.X{m} = eval(sprintf('%s(learning_indices, :)', view_names{m}));
prediction.X{m} = eval(sprintf('%s(prediction_indices, :)', view_names{m}));
end
learning.Y = eval('drug_source(learning_indices, :)');
validation.Y = eval('drug_source(prediction_indices, :)');
Ndrug = size(learning.Y, 2);
seed = 1606;
rand('state', seed); %#ok<RAND>
randn('state', seed); %#ok<RAND>
%%%% view normalization
for m = 1:P
nan_indices_learning = isnan(learning.X{m});
nan_indices_prediction = isnan(prediction.X{m});
if strcmp(view_kernels{m}, 'jaccard') ~= 1
mas.mea = nanmean(learning.X{m}, 1);
mas.std = nanstd(learning.X{m}, 0, 1);
mas.std(mas.std == 0) = 1;
learning.X{m} = bsxfun(@rdivide, bsxfun(@minus, learning.X{m}, mas.mea), mas.std);
prediction.X{m} = bsxfun(@rdivide, bsxfun(@minus, prediction.X{m}, mas.mea), mas.std);
end
learning.X{m}(nan_indices_learning) = 0;
prediction.X{m}(nan_indices_prediction) = 0;
end
%%%% drug response standardization
if standardize_response == 0
mas.mea = nanmean(learning.Y, 1);
learning.Y = bsxfun(@minus, learning.Y, mas.mea);
validation.Y = bsxfun(@minus,validation.Y , mas.mea);
else
mas.mea = nanmean(learning.Y, 1);
mas.std = nanstd(learning.Y, 0, 1);
mas.std(mas.std == 0) = 1;
learning.Y = bsxfun(@rdivide, bsxfun(@minus, learning.Y, mas.mea), mas.std);
validation.Y = bsxfun(@rdivide, bsxfun(@minus, validation.Y, mas.mea), mas.std);
end
validation_response_CV(k,:) = validation.Y;
%%%% kernels for views
Kx_learning = zeros(Nlearning, Nlearning, P);
Kx_prediction = zeros(Nlearning, Nprediction, P);
for m = 1:P
if strcmp(view_kernels{m}, 'gaussian') == 1
Kx_learning(:, :, m) = exp(-pdist2(learning.X{m}, learning.X{m}).^2 / size(learning.X{m}, 2) / 2);
Kx_prediction(:, :, m) = exp(-pdist2(learning.X{m}, prediction.X{m}).^2 / size(learning.X{m}, 2) / 2);
elseif strcmp(view_kernels{m}, 'exponential') == 1
Kx_learning(:, :, m) = exp(-pdist2(learning.X{m}, learning.X{m}) / sqrt(size(learning.X{m}, 2) ));
Kx_prediction(:, :, m) = exp(-pdist2(learning.X{m}, prediction.X{m}) / sqrt(size(learning.X{m}, 2) ));
elseif strcmp(view_kernels{m}, 'jaccard') == 1
J = 1 - pdist2(learning.X{m}, learning.X{m}, 'jaccard');
J(isnan(J)) = 0;
for j = 1:size(J, 1)
J(j, j) = 1;
end
Kx_learning(:, :, m) = J;
J = 1 - pdist2(learning.X{m}, prediction.X{m}, 'jaccard');
J(isnan(J)) = 0;
Kx_prediction(:, :, m) = J;
end
end
%%%% NCI/DREAM7 parameters
parameters.alpha_lambda = 1e-10; %positive
parameters.beta_lambda = 1e-10; %positive
parameters.alpha_upsilon = 1; %positive
parameters.beta_upsilon = 1; %positive
parameters.alpha_gamma = 1e-10; %positive
parameters.beta_gamma = 1e-10; %positive
parameters.alpha_omega = 1e-10; %positive
parameters.beta_omega = 1e-10; %positive
parameters.alpha_epsilon = 1; %positive
parameters.beta_epsilon = 1; %positive
parameters.iteration = 200;
parameters.seed = 1606;
%%%% combined kernel
K_learning = cell(1, Ndrug);
y_learning = cell(1, Ndrug);
K_prediction = cell(1, Ndrug);
for i = 1:Ndrug
indices = find(isnan(learning.Y(:, i)) == 0);
K_learning{i} = zeros(length(indices), length(indices), P);
for m = 1:P
K_learning{i}(:, :, m) = Kx_learning(indices, indices, m);
end
y_learning{i} = learning.Y(indices, i);
K_prediction{i} = zeros(size(Kx_prediction, 2), length(indices), P);
for m = 1:P
K_prediction{i}(:, :, m) = Kx_prediction(indices, :, m)';
end
end
state = bemkl_supervised_multitask_regression_variational_train(K_learning, y_learning, parameters);
output = bemkl_supervised_multitask_regression_variational_test(K_prediction, state);
predicted_response=zeros(length(prediction_indices), Ndrug);
for drug = 1:Ndrug
predicted_response(:, drug) = output.f{drug}.mean;
end
predicted_response_CV(k,:) = predicted_response;
end
end
|
github
|
yanlirock/Multi-task_Survival_Analysis-master
|
example_cox_CMTL.m
|
.m
|
Multi-task_Survival_Analysis-master/example_cox_CMTL.m
| 1,706 |
utf_8
|
e4b3f847365c131b1c42bf66d36edfcd
|
%% file example_cox_CMTL.m
% this file shows the usage of cox_CMTL.m function
function example_cox_CMTL(floder, name_train,name_test,lam_iter,clus_num,Smallest_lambda_rate)
current_path=cd;
Num_lambda=str2num(lam_iter);
smallest_rate=str2double(Smallest_lambda_rate);
addpath(genpath([current_path '/functions/'])); % load function
clus_num=str2num(clus_num);
% tell the direction where it contains train/test data.
dir=strcat(current_path,'/data/',floder);
load(strcat(dir,name_train,'.mat')); % load training data.
load(strcat(dir,name_test,'.mat')); % load testing data.
task_num = size(train_cell,1); % total task number.
opts.init = 0; % guess start point from data.
opts.tFlag = 1; % terminate after relative objective value does not changes much.
opts.tol = 10^-5; % tolerance.
opts.maxIter = 1000; % maximum iteration number of optimization.
epsilon=10^-5;
rho_1 = 10;
%rho_2 = 10^0;
W_old = zeros((size(test_cell{1},2)-2),task_num);
%kmCMTL_OrderedModel = zeros(size(W));
%OrderedTrueModel = zeros(size(W));
Cindex=zeros(Num_lambda,task_num);
TYPE = zeros(task_num,Num_lambda);
%% testing
for ii=1:Num_lambda
rho_2=rho_1^(9-ii);
[W_learn, funcVal,funcVal_cox, M_learned]= cox_CMTL(train_cell, rho_1, rho_2, clus_num,W_old,opts);
for jj =1:task_num
predict=test_cell{jj}(:,3:end)*W_learn(:,jj);
Cindex(ii,jj)=getcindex_cox(predict,test_cell{jj}(:,1),test_cell{jj}(:,2));
end
W_old=W_learn;
[U,S,V] = svd(M_learned);
tS=S(1:clus_num,:);
[M,I] = max(abs(tS*V));
TYPE(:,ii)=I';
end
% shows the best possible Cindex with different parameter
maxc=max(Cindex);
disp(maxc);
end
|
github
|
yanlirock/Multi-task_Survival_Analysis-master
|
multi_cox_prepare.m
|
.m
|
Multi-task_Survival_Analysis-master/multi_cox_prepare.m
| 4,835 |
utf_8
|
0fea2f9f280db4dc0227666bfb531de5
|
% This function is used to prapare the training and testing file for
% multi_task survival analysis. Beside cross validation it will also
% do preprocess for Cox model
function multi_cox_prepare(folder, num_cv)
% Detailed explanation goes here
%clear all;
n_num_cv=str2double(num_cv);
current_path=cd;
cd(strcat(current_path,folder)); %'/Noname_addone_miRNA_use/'
dd=dir('*.csv');
fileNames = {dd.name};
ntask=numel(fileNames);
data = cell(ntask,3);
data(:,1) = regexprep(fileNames, '.csv','');
mkdir(strcat(cd,'/cv'))
for ii = 1:ntask
%disp(ii);
data{ii,2} = dlmread(fileNames{ii});
cvf = crossvalind('Kfold',data{ii,2}(:,2),n_num_cv); % devide into train and test
data{ii,3} = cvf;
csvwrite(strcat(cd,'/cv/cv_',num2str(ii),'.csv'),cvf)
end
%% merge and cv
for k =1:n_num_cv
train_cell=cell(ntask,1);
test_cell=cell(ntask,1);
for j=1:ntask
test = (data{j,3} == k);
train = (data{j,3} ~= k);
test_cell{j}=data{j,2}(test,:);
train_cell{j}=cox_preprocess(data{j,2}(train,3:end),data{j,2}(train,1),'censoring',~(data{j,2}(train,2)));
end
save(strcat(cd,'/train_',num2str(k),'.mat'),'train_cell');
save(strcat(cd,'/test_',num2str(k),'.mat'),'test_cell');
end
cd(current_path);
%% cox_preprocess
function [Processed] = cox_preprocess(X,y,varargin)
% [...] = cox_preprocess(X,Y,'PARAM1',VALUE1,'PARAM2',VALUE2,...) specifies
% additional parameter name/value pairs chosen from the following:
%
% Name Value
% 'baseline' The X values at which the baseline hazard is to be
% computed. Default is mean(X), so the hazard at X is
% h(t)*exp((X-mean(X))*B). Enter 0 to compute the
% baseline relative to 0, so the hazard at X is
% h(t)*exp(X*B).
% 'censoring' A boolean array of the same size as Y that is 1 for
% observations that are right-censored and 0 for
% observations that are observed exactly. Default is
% all observations observed exactly.
% 'frequency' An array of the same size as Y containing non-negative
% integer counts. The jth element of this vector
% gives the number of times the jth element of Y and
% the jth row of X were observed. Default is 1
% observation per row of X and Y.
% 'init' A vector containing initial values for the estimated
% coefficients B.
% 'options' A structure specifying control parameters for the
% iterative algorithm used to estimate B. This argument
% can be created by a call to STATSET. For parameter
% names and default values, type STATSET('coxphfit').
narginchk(2,inf);
% Check the required data arguments
if ndims(X)>2 || ~isreal(X)
error(message('stats:coxphfit:BadX'));
end
if ~isvector(y) || ~isreal(y)
error(message('stats:coxphfit:BadY'));
end
% Process the optional arguments
okargs = {'baseline' 'censoring' 'frequency' 'init' 'options'};
defaults = {[] [] [] [] []};
[baseX cens freq init options] = internal.stats.parseArgs(okargs,defaults,varargin{:});
if ~isempty(cens) && (~isvector(cens) || ~all(ismember(cens,0:1)))
error(message('stats:coxphfit:BadCensoring'));
end
if ~isempty(freq) && (~isvector(freq) || ~isreal(freq) || any(freq<0))
error(message('stats:coxphfit:BadFrequency'));
end
if ~isempty(baseX) && ~(isnumeric(baseX) && (isscalar(baseX) || ...
(isvector(baseX) && length(baseX)==size(X,2))))
error(message('stats:coxphfit:BadBaseline'));
elseif isscalar(baseX)
baseX = repmat(baseX,1,size(X,2));
end
% Sort by increasing time
[sorty,idx] = sort(y);
X = X(idx,:);
[n,p] = size(X);
if isempty(cens)
cens = false(n,1);
else
cens = cens(idx);
end
if isempty(freq)
freq = ones(n,1);
else
freq = freq(idx);
end
% Determine the observations at risk at each time
[~,atrisk] = ismember(sorty,flipud(sorty), 'legacy');
atrisk = length(sorty) + 1 - atrisk; % "atrisk" used in nested function
tied = diff(sorty) == 0;
tied = [false;tied] | [tied;false]; % "tied" used in nested function
Processed = struct('X',X,'freq',freq,'cens',cens,'atrisk',atrisk);
end
end
|
github
|
yanlirock/Multi-task_Survival_Analysis-master
|
cox_L21.m
|
.m
|
Multi-task_Survival_Analysis-master/functions/cox_L21.m
| 5,214 |
utf_8
|
8688603ca548670a84a88f53d5e9e42a
|
%% FUNCTION Logistic_TGL
% L21 Joint Feature Learning with Coxph Loss.
%% Code starts here
function [W, funcVal] = cox_L21(cox_processed, W0, rho1, opts)
if nargin <3
error('\n Inputs: cox_processed, W0, rho1, should be specified!\n');
end
if nargin <4
opts = [];
end
% initialize options.
%opts=init_opts(opts);
if isfield(opts, 'rho_L2')
rho_L2 = opts.rho_L2;
else
rho_L2 = 0;
end
task_num = size(cox_processed,1);
dimension = size(cox_processed{1}.X, 2);
funcVal = [];
bFlag=0; % this flag tests whether the gradient step only changes a little
Wz= W0;
Wz_old = W0;
t = 1;
t_old = 0;
iter = 0;
gamma = 1;
gamma_inc = 2;
while iter < opts.maxIter
alpha = (t_old - 1) /t;
Ws = (1 + alpha) * Wz - alpha * Wz_old;
% compute function value and gradients of the search point
[gWs, Fs] = gradVal_eval(Ws);
while true
Wzp = FGLasso_projection(Ws - gWs/gamma, rho1 / gamma);
Fzp = funVal_eval (Wzp);
delta_Wzp = Wzp - Ws;
r_sum = norm(delta_Wzp, 'fro')^2;
% Fzp_gamma = Fs + trace(delta_Wzp' * gWs)...
% + gamma/2 * norm(delta_Wzp, 'fro')^2;
Fzp_gamma = Fs + sum(sum(delta_Wzp.* gWs))...
+ gamma/2 * norm(delta_Wzp, 'fro')^2;
if (r_sum <=1e-20)
bFlag=1; % this shows that, the gradient step makes little improvement
break;
end
if (Fzp <= Fzp_gamma)
break;
else
gamma = gamma * gamma_inc;
end
end
Wz_old = Wz;
Wz = Wzp;
funcVal = cat(1, funcVal, Fzp + nonsmooth_eval(Wz, rho1));
if (bFlag)
% fprintf('\n The program terminates as the gradient step changes the solution very small.');
break;
end
% test stop condition.
switch(opts.tFlag)
case 0
if iter>=2
if (abs( funcVal(end) - funcVal(end-1) ) <= opts.tol)
break;
end
end
case 1
if iter>=2
if (abs( funcVal(end) - funcVal(end-1) ) <=...
opts.tol* funcVal(end-1))
break;
end
end
case 2
if ( funcVal(end)<= opts.tol)
break;
end
case 3
if iter>=opts.maxIter
break;
end
end
iter = iter + 1;
t_old = t;
t = 0.5 * (1 + (1+ 4 * t^2)^0.5);
end
W = Wzp;
% private functions
function [Wp] = FGLasso_projection (W, lambda )
% solve it in row wise (L_{2,1} is row coupled).
% for each row we need to solve the proximal opterator
% argmin_w { 0.5 \|w - v\|_2^2 + lambda_3 * \|w\|_2 }
nm=sqrt(sum(W.^2,2));
Wp = bsxfun(@times,max(nm-lambda,0)./nm,W);
Wp(isnan(Wp))=0;
end
function [grad_W, funcVal] = gradVal_eval(W)
grad_W = zeros(dimension, task_num);
for i = 1:task_num
[ grad_W(:, i)] = gradandorg_neglogparlike(W(:, i),cox_processed{i});
end
grad_W = grad_W + rho_L2 * 2 * W;
% here when computing function value we do not include
% l1 norm.
funcVal = 0;
for i = 1: task_num
funcVal = funcVal + neglogparlike(W(:, i),cox_processed{i});
end
funcVal = funcVal + rho_L2 * norm(W,'fro')^2;
end
function [funcVal] = funVal_eval (W)
funcVal = 0;
for i = 1: task_num
funcVal = funcVal + neglogparlike(W(:, i),cox_processed{i});
end
% here when computing function value we do not include
% l1 norm.
funcVal = funcVal + rho_L2 * norm(W,'fro')^2;
end
function [non_smooth_value] = nonsmooth_eval(W, rho_1)
non_smooth_value = 0;
for i = 1 : size(W, 1)
w = W(i, :);
non_smooth_value = non_smooth_value ...
+ rho_1 * norm(w, 2);
end
end
end
function [L]=neglogparlike(b,cox_processed)
% Compute log likelihood L
X=cox_processed.X;
freq=cox_processed.freq;
cens=cox_processed.cens;
atrisk=cox_processed.atrisk;
obsfreq = freq .* ~cens;
Xb = X*b;
r = exp(Xb);
risksum = flipud(cumsum(flipud(freq.*r)));
risksum = risksum(atrisk);
L = obsfreq'*(Xb - log(risksum));
L = -L;
end
function [dl]=gradandorg_neglogparlike(b,cox_processed)
% Compute log likelihood L
X=cox_processed.X;
freq=cox_processed.freq;
cens=cox_processed.cens;
atrisk=cox_processed.atrisk;
obsfreq = freq .* ~cens;
Xb = X*b;
r = exp(Xb);
risksum = flipud(cumsum(flipud(freq.*r)));
risksum = risksum(atrisk);
[n,p] = size(X);
Xr = X .* repmat(r.*freq,1,p);
Xrsum = flipud(cumsum(flipud(Xr)));
Xrsum = Xrsum(atrisk,:);
A = Xrsum ./ repmat(risksum,1,p);
dl = obsfreq' * (X-A);
dl = -dl';
end
|
github
|
yanlirock/Multi-task_Survival_Analysis-master
|
Cox_Trace.m
|
.m
|
Multi-task_Survival_Analysis-master/functions/Cox_Trace.m
| 4,053 |
utf_8
|
63bc478fd7d3d32581dc386a1606cc38
|
%% FUNCTION Least_Trace
% Trace-Norm Regularized Learning with Cox Loss.
%% Code starts here
function [W, funcVal] = Cox_Trace(cox_processed, W0, rho1, opts)
if nargin <3
error('\n Inputs: cox_processed, W0, rho1, should be specified!\n');
end
if nargin <4
opts = [];
end
% initialize options.
%opts=init_opts(opts);
if isfield(opts, 'rho_L2')
rho_L2 = opts.rho_L2;
else
rho_L2 = 0;
end
task_num = size(cox_processed,1);
dimension = size(cox_processed{1}.X, 2);
funcVal = [];
bFlag=0; % this flag tests whether the gradient step only changes a little
Wz= W0;
Wz_old = W0;
t = 1;
t_old = 0;
iter = 0;
gamma = 1;
gamma_inc = 2;
while iter < opts.maxIter
alpha = (t_old - 1) /t;
Ws = (1 + alpha) * Wz - alpha * Wz_old;
% compute function value and gradients of the search point
gWs = gradVal_eval(Ws);
Fs = funVal_eval (Ws);
while true
[Wzp Wzp_tn] = trace_projection(Ws - gWs/gamma, 2 * rho1 / gamma);
Fzp = funVal_eval (Wzp);
delta_Wzp = Wzp - Ws;
r_sum = norm(delta_Wzp, 'fro')^2;
%Fzp_gamma = Fs + trace(delta_Wzp' * gWs) + gamma/2 * norm(delta_Wzp, 'fro')^2;
Fzp_gamma = Fs + sum(sum(delta_Wzp .* gWs)) + gamma/2 * norm(delta_Wzp, 'fro')^2;
if (r_sum <=1e-20)
bFlag=1; % this shows that, the gradient step makes little improvement
break;
end
if (Fzp <= Fzp_gamma)
break;
else
gamma = gamma * gamma_inc;
end
end
Wz_old = Wz;
Wz = Wzp;
%funcVal = cat(1, funcVal, Fzp + rho1 * sum( svd(Wzp, 0) ));
funcVal = cat(1, funcVal, Fzp + rho1 * Wzp_tn);
if (bFlag)
% fprintf('\n The program terminates as the gradient step changes the solution very small.');
break;
end
% test stop condition.
switch(opts.tFlag)
case 0
if iter>=2
if (abs( funcVal(end) - funcVal(end-1) ) <= opts.tol)
break;
end
end
case 1
if iter>=2
if (abs( funcVal(end) - funcVal(end-1) ) <=...
opts.tol* funcVal(end-1))
break;
end
end
case 2
if ( funcVal(end)<= opts.tol)
break;
end
case 3
if iter>=opts.maxIter
break;
end
end
iter = iter + 1;
t_old = t;
t = 0.5 * (1 + (1+ 4 * t^2)^0.5);
end
W = Wzp;
% private functions
function [grad_W] = gradVal_eval(W)
grad_W = zeros(dimension, task_num);
for i = 1:task_num
[ grad_W(:, i)] = gradandorg_neglogparlike(W(:, i),cox_processed{i});
end
grad_W = grad_W + rho_L2 * 2 * W;
end
function [funcVal] = funVal_eval (W)
funcVal = 0;
for i = 1: task_num
funcVal = funcVal + neglogparlike(W(:, i),cox_processed{i});
end
funcVal = funcVal + rho_L2 * norm(W, 'fro')^2;
end
end
function [L]=neglogparlike(b,cox_processed)
% Compute log likelihood L
X=cox_processed.X;
freq=cox_processed.freq;
cens=cox_processed.cens;
atrisk=cox_processed.atrisk;
obsfreq = freq .* ~cens;
Xb = X*b;
r = exp(Xb);
risksum = flipud(cumsum(flipud(freq.*r)));
risksum = risksum(atrisk);
L = obsfreq'*(Xb - log(risksum));
L = -L;
end
function [dl]=gradandorg_neglogparlike(b,cox_processed)
% Compute log likelihood L
X=cox_processed.X;
freq=cox_processed.freq;
cens=cox_processed.cens;
atrisk=cox_processed.atrisk;
obsfreq = freq .* ~cens;
Xb = X*b;
r = exp(Xb);
risksum = flipud(cumsum(flipud(freq.*r)));
risksum = risksum(atrisk);
[n,p] = size(X);
Xr = X .* repmat(r.*freq,1,p);
Xrsum = flipud(cumsum(flipud(Xr)));
Xrsum = Xrsum(atrisk,:);
A = Xrsum ./ repmat(risksum,1,p);
dl = obsfreq' * (X-A);
dl = -dl';
end
|
github
|
yanlirock/Multi-task_Survival_Analysis-master
|
cox_CMTL.m
|
.m
|
Multi-task_Survival_Analysis-master/functions/cox_CMTL.m
| 6,675 |
utf_8
|
bdabaa2c5864cee534765bccb59aa949
|
%% FUNCTION cox_CMTL
% Convex-relaxed Clustered Multi-Task Learning with Cox prprotional Loss.
%% Code starts here
function [W, funcVal,funcVal_cox, M] = cox_CMTL(cox_processed,rho1, rho2, k, W_old, opts)
if nargin <4
error('\n Inputs: cox_processed,rho1, rho2,and k should be specified!\n');
end
if nargin <5
opts = [];
end
if rho2<=0 || rho1<=0
error('rho1 and rho2 should both greater than zero.');
end
% if exist('mosekopt','file')==0
% error('Mosek is not found. Please install Mosek first. \n')
% end
% initialize options.
%opts=init_opts(opts);
task_num = size(cox_processed,1);
funcVal = [];
funcVal_cox= [];
eta = rho2 / rho1;
c = rho1 * eta * (1 + eta);
M0 = speye (task_num) * k / task_num;
bFlag=0; % this flag tests whether the gradient step only changes a little
Wz= W_old;
Wz_old = W_old;
Mz = M0;
Mz_old = M0;
t = 1;
t_old = 0;
iter = 0;
gamma = 1;
gamma_inc = 2;
while iter < opts.maxIter
alpha = (t_old - 1) /t;
Ws = (1 + alpha) * Wz - alpha * Wz_old;
Ms = (1 + alpha) * Mz - alpha * Mz_old;
% compute function value and gradients of the search point
%gWs = gradVal_eval(Ws, rho1);
%Fs = funVal_eval (Ws, rho1);
[gWs, gMs, Fs] = gradVal_eval (Ws, Ms);
while true
% [Wzp l1c_wzp] = l1_projection(Ws - gWs/gamma, 2 * rho2 / gamma);
% Fzp = funVal_eval (Wzp, rho1);
Wzp = Ws - gWs/gamma;
[Mzp ,Mzp_Pz, Mzp_DiagSigz ] = singular_projection (Ms - gMs/gamma, k);
[Fzp, F_cox] = funVal_eval (Wzp, Mzp_Pz, Mzp_DiagSigz);
%Fzp_gamma = Fs + trace(delta_Wzp' * gWs) + gamma/2 * norm(delta_Wzp, 'fro')^2;
delta_Wzs = Wzp - Ws;
delta_Mzs = Mzp - Ms;
r_sum = (norm(delta_Wzs, 'fro')^2 + norm(delta_Mzs, 'fro')^2)/2;
% Fzp_gamma = Fs + trace( (delta_Wzs)' * gWs) ...
% + trace( (delta_Mzs)' * gMs) ...
% + gamma/2 * norm(delta_Wzs, 'fro')^2 ...
% + gamma/2 * norm(delta_Mzs, 'fro')^2;
Fzp_gamma = Fs + sum(sum( delta_Wzs .* gWs)) ...
+ sum(sum( delta_Mzs .* gMs)) ...
+ gamma/2 * norm(delta_Wzs, 'fro')^2 ...
+ gamma/2 * norm(delta_Mzs, 'fro')^2;
if (r_sum <=eps)
bFlag=1; % this shows that, the gradient step makes little improvement
break;
end
if (Fzp <= Fzp_gamma)
break;
else
gamma = gamma * gamma_inc;
end
end
Wz_old = Wz;
Wz = Wzp;
Mz_old = Mz;
Mz = Mzp;
funcVal = cat(1, funcVal, Fzp);
funcVal_cox = cat(1, funcVal_cox, F_cox);
if (bFlag)
% fprintf('\n The program terminates as the gradient step changes the solution very small.');
break;
end
% test stop condition.
switch(opts.tFlag)
case 0
if iter>=2
if (abs( funcVal(end) - funcVal(end-1) ) <= opts.tol)
break;
end
end
case 1
if iter>=2
if (abs( funcVal(end) - funcVal(end-1) ) <=...
opts.tol* funcVal(end-1))
break;
end
end
case 2
if ( funcVal(end)<= opts.tol)
break;
end
case 3
if iter>=opts.maxIter
break;
end
end
iter = iter + 1;
t_old = t;
t = 0.5 * (1 + (1+ 4 * t^2)^0.5);
end
W = Wzp;
M = Mzp;
% private functions
function [Mzp, Mzp_Pz, Mzp_DiagSigz ] = singular_projection (Msp, k)
[EVector, EValue] = eig(Msp);
Pz = real(EVector); diag_EValue = real(diag(EValue));
%DiagSigz = SingVal_Projection(diag_EValue, k); % use mosek
DiagSigz = bsa_ihb(diag_EValue, ones(size(diag_EValue)), k, ones(size(diag_EValue)));
Mzp = Pz * diag(DiagSigz) *Pz';
Mzp_Pz = Pz;
Mzp_DiagSigz = DiagSigz;
end
% the negtive partial_likelihood of Cox model
function [L]=neglogparlike(b,cox_processed)
% Compute log likelihood L
X=cox_processed.X;
freq=cox_processed.freq;
cens=cox_processed.cens;
atrisk=cox_processed.atrisk;
obsfreq = freq .* ~cens;
Xb = X*b;
r = exp(Xb);
risksum = flipud(cumsum(flipud(freq.*r)));
risksum = risksum(atrisk);
L = obsfreq'*(Xb - log(risksum));
L = -L;
end
% the gradient of negtive partial_likelihood of Cox model
function [dl]=gradandorg_neglogparlike(b,cox_processed)
% Compute log likelihood L
X=cox_processed.X;
freq=cox_processed.freq;
cens=cox_processed.cens;
atrisk=cox_processed.atrisk;
obsfreq = freq .* ~cens;
Xb = X*b;
r = exp(Xb);
risksum = flipud(cumsum(flipud(freq.*r)));
risksum = risksum(atrisk);
[n,p] = size(X);
Xr = X .* repmat(r.*freq,1,p);
Xrsum = flipud(cumsum(flipud(Xr)));
Xrsum = Xrsum(atrisk,:);
A = Xrsum ./ repmat(risksum,1,p);
dl = obsfreq' * (X-A);
dl = -dl';
end
function [grad_W, grad_M, funcVal] = gradVal_eval(W ,M)
IM = (eta * speye(task_num) + M);
invEtaMWt = IM\W';
grad_W = [];
for t_ii = 1:task_num
dl=gradandorg_neglogparlike(W(:,t_ii),cox_processed{t_ii});
grad_W = cat(2, grad_W, dl);
end
grad_W = grad_W + 2 * c * invEtaMWt'; %W component
grad_M = - c * (W' * W / IM /IM ); %M component
funcVal = 0;
for iii = 1: task_num
funcVal = funcVal+neglogparlike(W(:,iii),cox_processed{iii});
%funcVal = funcVal + 0.5 * norm (Y{i} - X{i}' * W(:, i))^2;
end
funcVal = funcVal + c * trace( W * invEtaMWt);
end
function [funcVal,funcValorg] = funVal_eval (W, M_Pz, M_DiagSigz)
invIM = M_Pz * (diag( 1./(eta + M_DiagSigz))) * M_Pz';
invEtaMWt = invIM * W';
funcVal = 0;
for i = 1: task_num
funcVal = funcVal+neglogparlike(W(:,i),cox_processed{i});
%funcVal = funcVal + 0.5 * norm (Y{i} - X{i}' * W(:, i))^2;
end
funcValorg = funcVal ;
funcVal = funcVal + c * trace( W * invEtaMWt);
end
end
|
github
|
yanlirock/Multi-task_Survival_Analysis-master
|
trace_projection.m
|
.m
|
Multi-task_Survival_Analysis-master/functions/trace_projection.m
| 845 |
utf_8
|
dd710458fa390abd7ddc25e47f8af341
|
%% FUNCTION trace_projection
% solves the Trace-norm projection problem.
%
%% OBJECTIVE
% argmin_X = 0.5 \|X - L\| + alpha/2 \|L\|
%
%
%% RELATED PAPERS
% [1] Cai et. al. A Singlar Value Thresholding Algorihtm for Matrix
% Completion.
function [L_hat L_tn] = trace_projection(L, alpha)
[d1 d2] = size(L);
if (d1 > d2)
[U S V] = svd(L, 0);
thresholded_value = diag(S) - alpha / 2;
diag_S = thresholded_value .* ( thresholded_value > 0 );
L_hat = U * diag(diag_S) * V';
L_tn = sum(diag_S);
else
new_L = L';
[U S V] = svd(new_L, 0);
thresholded_value = diag(S) - alpha / 2;
diag_S = thresholded_value .* ( thresholded_value > 0 );
L_hat = U * diag(diag_S) * V';
L_hat = L_hat';
L_tn = sum(diag_S);
end
|
github
|
yanlirock/Multi-task_Survival_Analysis-master
|
bsa_ihb.m
|
.m
|
Multi-task_Survival_Analysis-master/functions/bsa_ihb.m
| 1,215 |
utf_8
|
4fd0ebe89b57d6e51011d127f2f7b379
|
%% FUNCTION bsa_ihb
% Singular Projection
%
%% OBJECTIVE
% min 1/2*||x - a||_2^2
% s.t. b'*x = r, 0<= x <= u, b > 0
%
%
%% Related papers
%
% [1] KC. Kiwiel. On linear-time algorithms for the continuous
% quadratic knapsack problem, Journal of Optimization Theory
% and Applications, 2007
%
function [x_star,t_star,iter] = bsa_ihb(a,b,r,u)
% initilization
break_flag = 0;
t_l = a./b; t_u = (a - u)./b;
T = [t_l;t_u];
t_L = -inf; t_U = inf;
g_tL = 0; g_tU = 0;
iter = 0;
while ~isempty(T)
iter = iter + 1;
g_t = 0;
t_hat = median(T);
U = t_hat < t_u;
M = (t_u <= t_hat) & (t_hat <= t_l);
if sum(U)
g_t = g_t + b(U)'*u(U);
end
if sum(M)
g_t = g_t + sum(b(M).*(a(M) - t_hat*b(M)));
end
if g_t > r
t_L = t_hat;
T = T(T > t_hat);
g_tL = g_t;
elseif g_t < r
t_U = t_hat;
T = T(T < t_hat);
g_tU = g_t;
else
t_star = t_hat;
break_flag = 1;
break;
end
end
if ~break_flag
t_star = t_L - (g_tL -r)*(t_U - t_L)/(g_tU - g_tL);
end
x_star = min(max(0,a - t_star*b),u);
end
|
github
|
nappoo/contourlet-transform-master
|
wfb2rec.m
|
.m
|
contourlet-transform-master/wfb2rec.m
| 1,419 |
utf_8
|
a8eb98892d022925b472758e34d4640d
|
function x = wfb2rec(x_LL, x_LH, x_HL, x_HH, h, g)
% WFB2REC 2-D Wavelet Filter Bank Decomposition
%
% x = wfb2rec(x_LL, x_LH, x_HL, x_HH, h, g)
%
% Input:
% x_LL, x_LH, x_HL, x_HH: Four 2-D wavelet subbands
% h, g: lowpass analysis and synthesis wavelet filters
%
% Output:
% x: reconstructed image
% Make sure filter in a row vector
h = h(:)';
g = g(:)';
g0 = g;
len_g0 = length(g0);
ext_g0 = floor((len_g0 - 1) / 2);
% Highpass synthesis filter: G1(z) = -z H0(-z)
len_g1 = length(h);
c = floor((len_g1 + 1) / 2);
g1 = (-1) * h .* (-1) .^ ([1:len_g1] - c);
ext_g1 = len_g1 - (c + 1);
% Get the output image size
[height, width] = size(x_LL);
x_B = zeros(height * 2, width);
x_B(1:2:end, :) = x_LL;
% Column-wise filtering
x_L = rowfiltering(x_B', g0, ext_g0)';
x_B(1:2:end, :) = x_LH;
x_L = x_L + rowfiltering(x_B', g1, ext_g1)';
x_B(1:2:end, :) = x_HL;
x_H = rowfiltering(x_B', g0, ext_g0)';
x_B(1:2:end, :) = x_HH;
x_H = x_H + rowfiltering(x_B', g1, ext_g1)';
% Row-wise filtering
x_B = zeros(2*height, 2*width);
x_B(:, 1:2:end) = x_L;
x = rowfiltering(x_B, g0, ext_g0);
x_B(:, 1:2:end) = x_H;
x = x + rowfiltering(x_B, g1, ext_g1);
% Internal function: Row-wise filtering with border handling
function y = rowfiltering(x, f, ext1)
ext2 = length(f) - ext1 - 1;
x = [x(:, end-ext1+1:end) x x(:, 1:ext2)];
y = conv2(x, f, 'valid');
|
github
|
nappoo/contourlet-transform-master
|
wfb2dec.m
|
.m
|
contourlet-transform-master/wfb2dec.m
| 1,359 |
utf_8
|
cf0a7abcc9abae631039550460b07a48
|
function [x_LL, x_LH, x_HL, x_HH] = wfb2dec(x, h, g)
% WFB2DEC 2-D Wavelet Filter Bank Decomposition
%
% y = wfb2dec(x, h, g)
%
% Input:
% x: input image
% h, g: lowpass analysis and synthesis wavelet filters
%
% Output:
% x_LL, x_LH, x_HL, x_HH: Four 2-D wavelet subbands
% Make sure filter in a row vector
h = h(:)';
g = g(:)';
h0 = h;
len_h0 = length(h0);
ext_h0 = floor(len_h0 / 2);
% Highpass analysis filter: H1(z) = -z^(-1) G0(-z)
len_h1 = length(g);
c = floor((len_h1 + 1) / 2);
% Shift the center of the filter by 1 if its length is even.
if mod(len_h1, 2) == 0
c = c + 1;
end
h1 = - g .* (-1).^([1:len_h1] - c);
ext_h1 = len_h1 - c + 1;
% Row-wise filtering
x_L = rowfiltering(x, h0, ext_h0);
x_L = x_L(:, 1:2:end);
x_H = rowfiltering(x, h1, ext_h1);
x_H = x_H(:, 1:2:end);
% Column-wise filtering
x_LL = rowfiltering(x_L', h0, ext_h0)';
x_LL = x_LL(1:2:end, :);
x_LH = rowfiltering(x_L', h1, ext_h1)';
x_LH = x_LH(1:2:end, :);
x_HL = rowfiltering(x_H', h0, ext_h0)';
x_HL = x_HL(1:2:end, :);
x_HH = rowfiltering(x_H', h1, ext_h1)';
x_HH = x_HH(1:2:end, :);
% Internal function: Row-wise filtering with border handling
function y = rowfiltering(x, f, ext1)
ext2 = length(f) - ext1 - 1;
x = [x(:, end-ext1+1:end) x x(:, 1:ext2)];
y = conv2(x, f, 'valid');
|
github
|
nappoo/contourlet-transform-master
|
extend2.m
|
.m
|
contourlet-transform-master/extend2.m
| 1,861 |
utf_8
|
40bc6d67909280efd214bb2536a4a46f
|
function y = extend2(x, ru, rd, cl, cr, extmod)
% EXTEND2 2D extension
%
% y = extend2(x, ru, rd, cl, cr, extmod)
%
% Input:
% x: input image
% ru, rd: amount of extension, up and down, for rows
% cl, cr: amount of extension, left and rigth, for column
% extmod: extension mode. The valid modes are:
% 'per': periodized extension (both direction)
% 'qper_row': quincunx periodized extension in row
% 'qper_col': quincunx periodized extension in column
%
% Output:
% y: extended image
%
% Note:
% Extension modes 'qper_row' and 'qper_col' are used multilevel
% quincunx filter banks, assuming the original image is periodic in
% both directions. For example:
% [y0, y1] = fbdec(x, h0, h1, 'q', '1r', 'per');
% [y00, y01] = fbdec(y0, h0, h1, 'q', '2c', 'qper_col');
% [y10, y11] = fbdec(y1, h0, h1, 'q', '2c', 'qper_col');
%
% See also: FBDEC
[rx, cx] = size(x);
switch extmod
case 'per'
I = getPerIndices(rx, ru, rd);
y = x(I, :);
I = getPerIndices(cx, cl, cr);
y = y(:, I);
case 'qper_row'
rx2 = round(rx / 2);
y = [[x(rx2+1:rx, cx-cl+1:cx); x(1:rx2, cx-cl+1:cx)], x, ...
[x(rx2+1:rx, 1:cr); x(1:rx2, 1:cr)]];
I = getPerIndices(rx, ru, rd);
y = y(I, :);
case 'qper_col'
cx2 = round(cx / 2);
y = [x(rx-ru+1:rx, cx2+1:cx), x(rx-ru+1:rx, 1:cx2); x; ...
x(1:rd, cx2+1:cx), x(1:rd, 1:cx2)];
I = getPerIndices(cx, cl, cr);
y = y(:, I);
otherwise
error('Invalid input for EXTMOD')
end
%----------------------------------------------------------------------------%
% Internal Function(s)
%----------------------------------------------------------------------------%
function I = getPerIndices(lx, lb, le)
I = [lx-lb+1:lx , 1:lx , 1:le];
if (lx < lb) | (lx < le)
I = mod(I, lx);
I(I==0) = lx;
end
|
github
|
spin0za/shadow-boundary-detection-master
|
buildFeatures.m
|
.m
|
shadow-boundary-detection-master/buildFeatures.m
| 3,852 |
utf_8
|
5104f9ea0ac10958a30e9938119e2117
|
% Calculating features for all edge (candidate) pixels
function features = buildFeatures(img, edgePixels, featNum)
dim = 36;
features = zeros(featNum, dim);
% gradient threshold to determine edge width
thresh = 0.1;
% compute 1st feature: Gaussian filter size = 2*support+1
sigma = 1;
support = 2;
sizeFilter = 2*support+1;
maxStep = 10;
imHeight = size(img, 1)+2*maxStep;
imWidth = size(img, 2)+2*maxStep;
nChannel = size(img, 3);
img = im2double(img);
for sc = 0:2
imgCopy = img;
if sc ~= 0
smoothGaussWidth = 6*sc+1;
f = fspecial('gaussian', smoothGaussWidth, sc);
for k = 1:nChannel
img(:, :, k) = conv2(img(:, :, k), f, 'same');
end
end
% expand image to avoid pixels out of bounds
Gmag = zeros(imHeight, imWidth, nChannel);
Gdir = zeros(imHeight, imWidth, nChannel);
imgNew = zeros(imHeight, imWidth, nChannel);
for k = 1:nChannel
imgNew(1:imHeight, 1:imWidth, k) = padarray(img(:, :, k), [maxStep, maxStep], 'replicate');
[Gmag(:, :, k), Gdir(:, :, k)] = imgradient(imgNew(:, :, k));
end
img = imgNew;
clear imgNew;
% loop through all edge pixels
for p = 1:featNum
pixel = edgePixels(p, :);
x = pixel(1)+maxStep;
y = pixel(2)+maxStep;
%% color gradient direction
gamma(1:nChannel) = Gdir(y, x, :);
gamma = gamma*pi/180;
% 3rd feature
gammaDiff = min([abs(gamma-gamma([2, 3, 1])); 2*pi-abs(gamma-gamma([2, 3, 1]))]);
%% illumination ratio & color gradient magnitude
% build oriented DoG filter
[u, v] = meshgrid(-support:support, -support:support);
theta = pi/2-gamma;
% leave out the constant coefficient
DoG = zeros(sizeFilter, sizeFilter, nChannel);
meanLeft = zeros(1, nChannel);
meanRight = zeros(1, nChannel);
for k = 1:nChannel
DoG(:, :, k) = -(u.*cos(theta(k))+v.*sin(theta(k))).*exp(-(u.^2+v.^2)/(2*sigma^2));
end
DoG(DoG<0) = 0;
for k = 1:nChannel
DoG(:, :, k) = DoG(:, :, k)./sum(sum(DoG(:, :, k)));
meanLeft(k) = sum(sum(DoG(sizeFilter:-1:1, sizeFilter:-1:1, k).*img(y-support:y+support, x-support:x+support, k)));
% rotate 180 degrees and convolve
meanRight(k) = sum(sum(DoG(:, :, k).*img(y-support:y+support, x-support:x+support, k)));
end
t = min([meanLeft; meanRight])./max([meanLeft; meanRight]);
% disp(nChannel);
% disp(meanLeft);
% disp(meanRight);
% 1st feature
t = [sum(t)/3, t(1)/t(3), t(2)/t(3)];
% 2nd feature
mag(1:nChannel) = Gmag(y, x, :);
delta = mag./max([meanLeft; meanRight]);
%% edge width
% [stepX, stepY]
step = [cos(gamma'), sin(gamma')];
w = zeros(1, nChannel);
for k = 1:nChannel
ridge = zeros(2, 2);
for dir = 1:2
xk = uint32(x+(-1)^dir*(1:maxStep)*step(k, 1));
yk = uint32(y+(-1)^dir*(1:maxStep)*step(k, 2));
ridge(dir, :) = double([xk(maxStep), yk(maxStep)]);
idk = (xk-1)*imHeight+yk;
id = find(Gmag(idk+(k-1)*imHeight*imWidth) < thresh*Gmag(y, x, k), 1);
id = idk(id);
if ~isempty(id)
ridge(dir, :) = double([ceil(id/imHeight), mod(id, imHeight)]);
end
end
w(k) = norm(ridge(2, :)-ridge(1, :));
end
% 4th feature
w = [sum(w)/3, w(1)/w(2), w(1)/w(3)];
%%
features(p, 12*sc+1:12*sc+3) = t;
features(p, 12*sc+4:12*sc+6) = delta;
features(p, 12*sc+7:12*sc+9) = gammaDiff;
features(p, 12*sc+10:12*sc+12) = w;
end
img = imgCopy;
end
end
|
github
|
fstasel/fastBilateral3d-master
|
bf3.m
|
.m
|
fastBilateral3d-master/bf3.m
| 2,726 |
utf_8
|
d1c304ecce7898e6b3ba7e3eddbb0401
|
% Fast 3d bilateral filter for unit8 images
% Coded by FST
%
% F. Porikli, “Constant time O (1) bilateral filtering,” Comput. Vis.
% Pattern Recognition, 2008. CVPR 2008. IEEE Conf., no. 1, pp. 1–8, 2008.
%
% Usage:
% Ibf = bf3(I, spatialSize, rangeSigma)
%
% I: input 3d image
%
% spatialSize: window size of spatial filtering
% (in terms of pixels)
% spatialSize can be very large
% and does not effect computation time
%
% rangeSigma: sigma size of range filtering
% (in terms of 0-255 gray values)
%
% Example:
% Ibf = bf3(I,7,10);
%
function Ibf = bf3(I, spatialSize, rangeSigma)
global BINS R;
BINS = 16;
R = 256 / BINS;
[sz,sy,sx] = size(I);
k = gkernel(rangeSigma);
Iq = uint8(1 + floor(double(I) ./ R));
Ibins = zeros(BINS, sz, sy, sx);
Ibins_int = zeros(BINS, sz+1, sy+1, sx+1);
for b = 1:BINS
Ibins(b,:,:,:) = (Iq(:,:,:) == b);
Ibins_int(b,:,:,:) = integralImage3(squeeze(Ibins(b,:,:,:)));
end
hWindow = uint8(floor(spatialSize / 2));
Ibf = zeros(sz,sy,sx);
for z = 1:sz
eR = z + hWindow;
sR = z - hWindow;
if sR < 1
sR = 1;
end
if eR > sz
eR = sz;
end
for y = 1:sy
eC = y + hWindow;
sC = y - hWindow;
if sC < 1
sC = 1;
end
if eC > sy
eC = sy;
end
for x = 1:sx
eP = x + hWindow;
sP = x - hWindow;
if sP < 1
sP = 1;
end
if eP > sx
eP = sx;
end
tw = 0;
ws = 0;
for b = 1:BINS
d = 1 + abs(Iq(z,y,x) - b);
s = Ibins_int(b,eR+1,eC+1,eP+1) ...
- Ibins_int(b,eR+1,eC+1,sP) ...
- Ibins_int(b,eR+1,sC,eP+1) ...
- Ibins_int(b,sR,eC+1,eP+1) ...
+ Ibins_int(b,sR,sC,eP+1) ...
+ Ibins_int(b,sR,eC+1,sP) ...
+ Ibins_int(b,eR+1,sC,sP) ...
- Ibins_int(b,sR,sC,sP);
w = s * k(d);
tw = tw + w;
ws = ws + (b-1) * w;
end
ws = ws / (tw * (BINS - 1));
Ibf(z,y,x) = uint8(255 * ws);
end
end
end
end
function h = gkernel(stdev)
global BINS R;
h=exp(-0.5 * R * ((0:BINS-1) / stdev).^2);
h=h./sum(h);
end
|
github
|
LLNL/psuade-master
|
lbfgsb.m
|
.m
|
psuade-master/External/L-BFGS-B-C/Matlab/lbfgsb.m
| 10,264 |
utf_8
|
cf0b737b65f70954855560be1aae6caf
|
function [x,f,info] = lbfgsb( fcn, l, u, opts )
% x = lbfgsb( fcn, l, u )
% uses the lbfgsb v.3.0 library (fortran files must be installed;
% see compile_mex.m ) which is the L-BFGS-B algorithm.
% The algorithm is similar to the L-BFGS quasi-Newton algorithm,
% but also handles bound constraints via an active-set type iteration.
% This version is based on the modified C code L-BFGS-B-C, and so has
% a slightly different calling syntax than previous versions.
%
% The minimization problem that it solves is:
% min_x f(x) subject to l <= x <= u
%
% 'fcn' is a function handle that accepts an input, 'x',
% and returns two outputs, 'f' (function value), and 'g' (function gradient).
%
% 'l' and 'u' are column-vectors of constraints. Set their values to Inf
% if you want to ignore them. (You can set some values to Inf, but keep
% others enforced).
%
% The full format of the function is:
% [x,f,info] = lbfgsb( fcn, l, u, opts )
% where the output 'f' has the value of the function f at the final iterate
% and 'info' is a structure with useful information
% (self-explanatory, except for info.err. The first column of info.err
% is the history of the function values f, and the second column
% is the history of norm( gradient, Inf ). )
%
% The 'opts' structure allows you to pass further options.
% Possible field name values:
%
% opts.x0 The starting value (default: all zeros)
% opts.m Number of limited-memory vectors to use in the algorithm
% Try 3 <= m <= 20. (default: 5 )
% opts.factr Tolerance setting (see this source code for more info)
% (default: 1e7 ). This is later multiplied by machine epsilon
% opts.pgtol Another tolerance setting, relating to norm(gradient,Inf)
% (default: 1e-5)
% opts.maxIts How many iterations to allow (default: 100)
% opts.maxTotalIts How many iterations to allow, including linesearch iterations
% (default: 5000)
% opts.printEvery How often to display information (default: 1)
% opts.errFcn A function handle (or cell array of several function handles)
% that computes whatever you want. The output will be printed
% to the screen every 'printEvery' iterations. (default: [] )
% Results saved in columns 3 and higher of info.err variable
%
% Stephen Becker, [email protected]
% Feb 14, 2012
% Updated Feb 21 2015, Stephen Becker, [email protected]
narginchk(3, 4)
if nargin < 4, opts = struct([]); end
% Matlab doesn't let you use the .name convention with structures
% if they are empty, so in that case, make the structure non-empty:
if isempty(opts), opts=struct('a',1) ; end
function out = setOpts( field, default, mn, mx )
if ~isfield( opts, field )
opts.(field) = default;
end
out = opts.(field);
if nargin >= 3 && ~isempty(mn) && any(out < mn), error('Value is too small'); end
if nargin >= 4 && ~isempty(mx) && any(out > mx), error('Value is too large'); end
opts = rmfield( opts, field ); % so we can do a check later
end
% [f,g] = callF( x );
if iscell(fcn)
% the user has given us separate functions to compute
% f (function) and g (gradient)
callF = @(x) fminunc_wrapper(x,fcn{1},fcn{2} );
else
callF = fcn;
end
n = length(l);
if length(u) ~= length(l), error('l and u must be same length'); end
x0 = setOpts( 'x0', zeros(n,1) );
x = x0 + 0; % important: we want Matlab to make a copy of this.
% just in case 'x' will be modified in-place
% (Feb 2015 version of code, it should not be modified,
% but just-in-case, may as well leave this )
if size(x0,2) ~= 1, error('x0 must be a column vector'); end
if size(l,2) ~= 1, error('l must be a column vector'); end
if size(u,2) ~= 1, error('u must be a column vector'); end
if size(x,1) ~= n, error('x0 and l have mismatchig sizes'); end
if size(u,1) ~= n, error('u and l have mismatchig sizes'); end
% Number of L-BFGS memory vectors
% From the fortran driver file:
% "Values of m < 3 are not recommended, and
% large values of m can result in excessive computing time.
% The range 3 <= m <= 20 is recommended. "
m = setOpts( 'm', 5, 0 );
% 'nbd' is 0 if no bounds, 1 if lower bound only,
% 2 if both upper and lower bounds, and 3 if upper bound only.
% This .m file assumes l=-Inf and u=+Inf imply that there are no constraints.
% So, convert this to the fortran convention:
nbd = isfinite(l) + isfinite(u) + 2*isinf(l).*isfinite(u);
if ispc
nbd = int32(nbd);
else
nbd = int64(nbd);
end
% Some scalar settings, "factr" and "pgtol"
% Their descriptions, from the fortran file:
% factr is a DOUBLE PRECISION variable that must be set by the user.
% It is a tolerance in the termination test for the algorithm.
% The iteration will stop when
%
% (f^k - f^{k+1})/max{|f^k|,|f^{k+1}|,1} <= factr*epsmch
%
% where epsmch is the machine precision which is automatically
% generated by the code. Typical values for factr on a computer
% with 15 digits of accuracy in double precision are:
% factr=1.d+12 for low accuracy;
% 1.d+7 for moderate accuracy;
% 1.d+1 for extremely high accuracy.
% The user can suppress this termination test by setting factr=0.
factr = setOpts( 'factr', 1e7, 0 );
% pgtol is a double precision variable.
% On entry pgtol >= 0 is specified by the user. The iteration
% will stop when
%
% max{|proj g_i | i = 1, ..., n} <= pgtol
%
% where pg_i is the ith component of the projected gradient.
% The user can suppress this termination test by setting pgtol=0.
pgtol = setOpts( 'pgtol', 1e-5, 0 ); % may crash if < 0
% Maximum number of outer iterations
maxIts = setOpts( 'maxIts', 100, 1 );
% Maximum number of total iterations
% (this includes the line search steps )
maxTotalIts = setOpts( 'maxTotalIts', 5e3 );
% Print out information this often (and set to Inf to suppress)
printEvery = setOpts( 'printEvery', 1 );
errFcn = setOpts( 'errFcn', [] );
iprint = setOpts('verbose',-1);
% <0 for no output, 0 for some, 1 for more, 99 for more, 100 for more
% I recommend you set this -1 and use the Matlab print features
% (e.g., set printEvery )
fcn_wrapper(); % initialized persistent variables
callF_wrapped = @(x,varargin) fcn_wrapper( callF, errFcn, maxIts, ...
printEvery, x, varargin{:} );
% callF_wrapped = @(x,varargin)callF(x); % also valid, but simpler
% Call the mex file
[f,x,taskInteger,outer_count, k] = lbfgsb_wrapper( m, x, l, u, nbd, ...
callF_wrapped, factr, pgtol, ...
iprint, maxIts, maxTotalIts);
info.iterations = outer_count;
info.totalIterations = k;
info.lbfgs_message1 = findTaskString( taskInteger );
errHist = fcn_wrapper();
info.err = errHist;
end % end of main function
function [f,g] = fcn_wrapper( callF, errFcn, maxIts, printEvery, x, varargin )
persistent k history
if isempty(k), k = 1; end
if nargin==0
% reset persistent variables and return information
if ~isempty(history) && ~isempty(k)
printFcn(k,history);
f = history(1:k,:);
end
history = [];
k = [];
return;
end
if isempty( history )
width = 0;
if iscell( errFcn ), width = length(errFcn);
elseif ~isempty(errFcn), width = 1; end
width = width + 2; % include fcn and norm(grad) as well
history = zeros( maxIts, width );
end
% Find function value and gradient:
[f,g] = callF(x);
if nargin > 5
outerIter = varargin{1}+1;
history(outerIter,1) = f;
history(outerIter,2) = norm(g,Inf); % g is not projected
if isa( errFcn, 'function_handle' )
history(outerIter,3) = errFcn(x);
elseif iscell( errFcn )
for j = 1:length(errFcn)
history(outer_count,j+2) = errFcn{j}(x);
end
end
if outerIter > k
% Display info from *previous* input
% Since this may be called several times before outerIter
% is actually updated
% fprintf('At iterate %5d, f(x)= %.2e, ||grad||_infty = %.2e [MATLAB]\n',...
% k,history(k,1),history(k,2) );
if ~isinf(printEvery) && ~mod(k,printEvery)
printFcn(k,history);
end
k = outerIter;
end
end
end
function printFcn(k,history)
fprintf('Iter %5d, f(x) = %2e, ||grad||_infty = %.2e', ...
k, history(k,1), history(k,2) );
for col = 3:size(history,2)
fprintf(', %.2e', history(k,col) );
end
fprintf('\n');
end
function [f,g] = fminunc_wrapper(x,F,G)
% [f,g] = fminunc_wrapper( x, F, G )
% for use with Matlab's "fminunc"
f = F(x);
if nargin > 2 && nargout > 1
g = G(x);
end
end
function str = findTaskString( taskInteger )
% See the #define statements in lbfgsb.h
switch taskInteger
case 209
str = 'ERROR: N .LE. 0';
case 210
str = 'ERROR: M .LE. 0';
case 211
str = 'ERROR: FACTR .LT. 0';
case 3
str = 'ABNORMAL_TERMINATION_IN_LNSRCH.';
case 4
str = 'RESTART_FROM_LNSRCH.';
case 21
str = 'CONVERGENCE: NORM_OF_PROJECTED_GRADIENT_<=_PGTOL.';
case 22
str = 'CONVERGENCE: REL_REDUCTION_OF_F_<=_FACTR*EPSMCH.';
case 31
str = 'STOP: CPU EXCEEDING THE TIME LIMIT.';
case 32
str = 'STOP: TOTAL NO. of f AND g EVALUATIONS EXCEEDS LIM.';
case 33
str = 'STOP: THE PROJECTED GRADIENT IS SUFFICIENTLY SMALL.';
case 101
str = 'WARNING: ROUNDING ERRORS PREVENT PROGRESS';
case 102
str = 'WARNING: XTOL TEST SATISIED';
case 103
str = 'WARNING: STP = STPMAX';
case 104
str = 'WARNING: STP = STPMIN';
case 201
str = 'ERROR: STP .LT. STPMIN';
case 202
str = 'ERROR: STP .GT. STPMAX';
case 203
str = 'ERROR: INITIAL G .GE. ZERO ';
case 204
str = 'ERROR: FTOL .LT. ZERO';
case 205
str = 'ERROR: GTOL .LT. ZERO';
case 206
str = 'ERROR: XTOL .LT. ZERO';
case 207
str = 'ERROR: STPMIN .LT. ZERO';
case 208
str = 'ERROR: STPMAX .LT. STPMIN';
case 212
str = 'ERROR: INVALID NBD';
case 213
str = 'ERROR: NO FEASIBLE SOLUTION';
otherwise
str = 'UNRECOGNIZED EXIT FLAG';
end
end
|
github
|
anantsrivastava30/SUVR-PET-ADNI-master
|
cvx_version.m
|
.m
|
SUVR-PET-ADNI-master/scripts/cvx/cvx_version.m
| 14,459 |
utf_8
|
9f358480cc5d66caa274c9d5bd5ed0de
|
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 = '1116';
cvx_bdate = 'Thu Mar 30 21:54:11 2017';
cvx_bcomm = 'd4cc5c5';
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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
cvx_grbgetkey.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
HSDNTcorr.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
HSDHKMdirfun.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
HSDsqlp.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
HSDsortA.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
HSDHKMrhsfun.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
HSDsqlpcheckconvg.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
HSDNTdirfun.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
HSDNTrhsfun.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
HSDHKMpred.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
HSDsqlpmain.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
HSDlinsysolve.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
HSDsqlpmisc.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
HSDbicgstab.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
HSDHKMcorr.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
HSDNTpred.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
HSDsqlpCpert.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
cheby0.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
randmat.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
skron.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
NTcorr.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
HKMcorr.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
steplength.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
SDPT3data_SEDUMIdata.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
schurmat_sblk.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
blktrace.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
sqlpu2lblk.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
Prod3.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
sqlptermcode.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
AXfun.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
NTpred.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
sqlp.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
infeaspt.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
Arrow.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
mybicgstab.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
degeneracy.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
mytime.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
validate.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
svec.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
read_sedumi.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
qprod.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
nzlist.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
detect_lblk.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
gdcomp.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
blkbarrier.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
sqlpmain.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
HKMpred.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
read_sdpa.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
sortA.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
blkeig.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
HKMrhsfun.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
linsysolve.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
schurmat_qblk.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
ops.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
schurmat_lblk.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
sqlpmisc.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
checkdense.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
NTrhsfun.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
SDPvalBounds.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
|
anantsrivastava30/SUVR-PET-ADNI-master
|
NTscaling.m
|
.m
|
SUVR-PET-ADNI-master/scripts/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
%%**********************************************************************
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.