% This code constructs input to SDPT3 to solve optimal design with D-criterion:
%
% minimize { -logdet(M(w)) : e^Tw=1, w>=0, M(w)>0},
% where M(w) = w_1A_1+...+w_mA_m and A_i are n by n psd matrices.
% 
% Input
% M - matrix whose ith column is formed from stacking columns of A_i together;
%
% Output
% w    - approximate optimal solution;
% fval - approximate optimal value.
% time - time for running SDPT3.
%
% Jan 12, 2012
% Written by Zhaosong Lu and Ting Kei Pong

function [w, fval, time] = D_criterion_SDPT3(M)

n = sqrt(size(M,1));
m = size(M,2);

blk{1,1} = 'l'; blk{1,2} = m;
blk{2,1} = 's'; blk{2,2} = n;

count = 1;
MA = zeros(n*(n+1)/2,m);
for j = 1:n
  for i = 1:j
    if i == j
      MA(count,:) = M(n*(i-1) + j,:);
      count = count + 1;
    end
    if i < j
      MA(count,:) = sqrt(2)*M(n*(i-1) + j,:);
      count = count + 1;
    end
  end
end

Aw = [MA;ones(1,m)];

A{1,1} = Aw';
C{1,1} = zeros(m,1);

Au = -eye(n*(n+1)/2);
Au = [Au;zeros(1,n*(n+1)/2)];

A{2,1} = Au';
C{2,1} = zeros(n,n);

b = [zeros(n*(n+1)/2,1);1];

OPTIONS.parbarrier{1} = [];
OPTIONS.parbarrier{2} = 1;

OPTIONS.printlevel = 0;
tic
[obj,X] = sdpt3(blk,A,C,b,OPTIONS); 
time = toc;

w = X{1};
w = simplex_proj(w,1);

X = reshape(M*w,n,n);

[V,D] = svd(X);

fval = -sum(log(diag(D)));   

fprintf(' fval = %g   \n', fval)