% This is generator of problems described in
% M.V. Solodov,
% ``A bundle method for a class of bilevel nonsmooth convex
% minimization problems'',
% SIAM Journal on Optimization, 18 (2007), 242-259.

function [d,Q,q,bx,bf,A1,A2,A3,A4,A5,b1,b2,b3,b4,b5,c1,c2,c3,c4,c5] = genbi();
%generate bilevel data

%d=5; %Rn
d=input(' enter demension ');

%complementarity part

%r=2; % -rank
r=input(' enter corank ');

E=5*(rand(d-r)-rand(d-r)); Q=E;
for i=1:r, Q=[Q; (E*rand(d-r,1))']; end;
Q=Q*Q';

bx = zeros(d,1);
by = zeros(d,1);

for i=1:d, 
  t=rand; if t >= .5 bx(i)=5*t; 
          else s=rand; if s >= .5 by(i)=5*s;end;
          end;
end;

q=-Q*bx+by;


%piecewise quadratic function with min at bx
%the first 3(2) out of 5 pieces are active at bx

v=rand(d); A1=v*v'; v=rand(d); A2=v*v'; v=rand(d); A3=v*v';
v=rand(d); A4=v*v'; v=rand(d); A5=v*v';

I=eye(d);
b1=-2.*A1*bx; 
%[z,zz]=min(bx); b1(zz)=b1(zz)-1;
%[z,zz]=min(by); b2=-2*A2*bx-Q(zz,:)';
ix=find(bx==0); iy=find(by==0);
b1=b1+I(ix,:)'*rand(length(ix),1)+Q(iy,:)'*rand(length(iy),1);
b1=b1-rand*(q+(Q+Q')*bx);
b2=-2.*A2*bx;
b2=b2+I(ix,:)'*rand(length(ix),1)+Q(iy,:)'*rand(length(iy),1);
b2=b2-rand*(q+(Q+Q')*bx);

b3=-2.*A3*bx;
b3=b3+I(ix,:)'*rand(length(ix),1)+Q(iy,:)'*rand(length(iy),1);
b3=b3-rand*(q+(Q+Q')*bx);
%b3=10*rand(d,1); 

b4=rand(d,1);b5=rand(d,1);

bc=max([bx'*A1*bx+b1'*bx,bx'*A2*bx+b2'*bx,bx'*A3*bx+b3'*bx]);  
bc=max([bc,bx'*A4*bx+b4'*bx,bx'*A5*bx+b5'*bx])+5;
c1=bc-bx'*A1*bx-b1'*bx; c2=bc-bx'*A2*bx-b2'*bx;

c3=bc-bx'*A3*bx-b3'*bx;
%c3=0;

c4=0;c5=0;

bf= bx'*A1*bx+b1'*bx+c1; %=bc

%save 'dmxq.mat' A1 A2 A3 A4 A5 b1 b2 b3 b4 b5 pen

