% Written by Vanja Dukic, 2000.
%
% Please cite: 
% Dukic and Gatsonis, “Meta-analysis of Diagnostic Test Accuracy Assessment Studies with Varying Number of Thresholds”, Biometrics, 59(4):936-946
% Any questions or comments, please contact me: vanja.dukic@colorado.edu
%
% Prof. Vanja Dukic
% Department of Applied Mathematics
% University of Colorado-Boulder
% Box 526; Boulder, CO 80309-0526
% tel: 303-735-0919; fax: 303-492-4066


function [L,dev]=lik(y,x,x1,beta,pr1,Link)
%       Calculates likelihood for ordinal logistic
%	regression model.

global stepr tol incr decr;
global K Link;

beta=beta(:);

j = range(y)+1;           % number of categories
p = size(x,2);            % number of loc covariates
p1 = size(x1,2);          % number of scale covariates
n = size(y,1);            % number of patients
bl=length(beta);
sc1=beta(bl);
sc=beta(bl-1);
b=beta(bl-2);

YJ = ( ones(n,1) * [1:j] ) == ( y * ones(1,j) );
TJ = ones(n,1) * beta( 1 : (j-1) )' ;
XJ = x * b  * ones(1, (j-1) );
X1J = exp(x * (pr1*sc1 + sc)  * ones(1, (j-1) ));


if Link == 1,     % logit
E = exp((TJ + XJ)./X1J )./(1+exp((TJ + XJ)./X1J ));
else,
E = cdf('norm', (TJ + XJ)./X1J ,0,1);
end;

E0 = [ zeros(n,1) , E ];
E1 = [ E, ones(n,1) ];


L = sum(sum( YJ .* log( E1 - E0 + eps) ) ) ;
dev = -2*L;




