function [ aa , bb ] = box_constraint(x,r,n)
% [ aa , bb ] = box_constraint(x,r)
% determine box constraint scaling factors (aa,bb) to the 
% perturbation vector r from x such that: 
% max(x+aa*r) < +1, min(x+aa*r) > -1, max(x-bb*r) < +1, and  min(x-bb*r) > -1, 
% with aa>0, bb>0

if ( nargin == 0 ) n=5; x = -1.0 + 2.0*rand(n,1); r=randn(n,1); end % test 

zn = zeros(n,1);
In = eye(n);
on = ones(n,1);
a  =  on;
b  = -on;

for i=1:n                           % loop over every dimension in the problem

   ei = zn;  ei(i) = 1;             % unit vector in dimension "i"
   Ii = In;  Ii(:,i) = -r;          % Identity with "i-th" colum = "-r"
   vab = Ii \ [ (x-ei) , (x+ei) ];  % i-th row of vab = +/- scaling to limits
   aa = vab(i,1);
   bb = vab(i,2);
   if (aa>0) a(i)=aa; b(i)=bb; else a(i)=bb; b(i)=aa; end % swap a & b

end

aa =  min(min(a),+1);
bb = -max(max(b),-1);

%{
% test
if ( nargin == 0 ) 
  pp = x + aa*r
  mm = x - bb*r
end
%}

%{
if ( nargin == 0 && n==2 ) 
  s = 1.1;
  figure(1)
   clf
   plot([-s,+s],[-1,-1],'-k', [-s,+s],[+1,+1],'--k',  ...
        [-1,-1],[-s,+s],'--k', [+1,+1],[-s,+s],'--k',  ...
         [x(1),x(1)+r(1)],[x(2),x(2)+r(2)],'-r', ...
         x(1),x(2),'or', x(1)+r(1), x(2)+r(2),'*r' , ...
         x(1)+aa*r(1), x(2)+aa*r(2),'xg' , ...
         [x(1),x(1)+aa*r(1)],[x(2),x(2)+aa*r(2)],'-g' , ...
         x(1)-bb*r(1), x(2)-bb*r(2),'xb' , ...
         [x(1),x(1)-bb*r(1)],[x(2),x(2)-bb*r(2)],'-b' );
    axis([-2 2 -2 2])
    axis('square')
    %% drawnow
    %% pause(1)
end
%} 

% ------------------------------------------------------------ box_constraint
% 2015-03-14  (pi day 3.14.15)

