% CRANK_TEST.M            05-31-2011          code by: Komunjer and Ng
% This function performs the rank test for conditional identification derived in
% Proposition 3 of Komunjer and Ng (2011). This is for the SINGULAR CASE. The ranks are computed for a
% range of tolerance levels.

function table2 = rank_test_res(Delta_0,n_theta,n_x,n_eps,n_y,tol,Restrict)

table2 = [];
n_required = n_theta+n_x^2+n_eps^2;
n_actual = rank(Delta_0,tol);
n_delta = (n_y*n_x + n_eps*(n_x+n_y-n_eps) + n_eps*(n_eps+1)/2);
table_n = [n_theta n_x^2 n_eps^2  n_theta+n_x^2 n_theta+n_eps^2 n_required 1];
for ir = 1:size(Restrict,2);
    restrict=Restrict{ir};
    n_restrict=cols(restrict);
    R=zeros(n_restrict,n_theta);
    for j=1:cols(restrict);
      R(j,restrict(j))=1;
    end;  
    psi=[R zeros(n_restrict,n_x^2+n_eps^2)];
    Delta_i=[psi; Delta_0];
    Delta_Li=Delta_i(:,1:n_theta);
    Delta_Ti=Delta_i(:,n_theta+1:n_theta+n_x^2);
    Delta_Ui=Delta_i(:,n_theta+n_x^2+1:end);
    n_actual=rank(Delta_i,tol);
    pass_order = (n_theta <= n_delta);
    pass_rank = (n_actual == n_required);
    table2=[table2; n_restrict rank(Delta_Li,tol) rank(Delta_Ti,tol)  rank(Delta_Ui,tol) ...
	         rank([Delta_Li Delta_Ti],tol)  rank([Delta_Li Delta_Ui],tol) ...
	    	 rank(Delta_i,tol) pass_rank];
end;  % end restrictions


% disp(sprintf('\n\n'));
% disp('** Conditional Tests **');
% disp(sprintf('n_theta = %d  n_x = %d  n_eps = %d   Tol = %5e',n_theta,n_x,n_eps,tol));
% fmt0=[  repmat('%5d&',1,cols(table2)-1) '%5d ' '\\\\'];
% fmt1=['%s',repmat('%5d&',1, cols(table_n)-1)  '%5d \\\\ '] ;
% disp(sprintf('\n  n_R    DL     DT    DU    LT    LU   LTU  pass'));
% for i=1:rows(table2);
%     disp(sprintf(fmt0,table2(i,:)));
% end;
% disp(sprintf(fmt1,'Require', table_n(1,:)));




