% 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 [dl,d2l]=derivs(y,x,x1,beta,pr1)
%       Calculates derivates of log-likelihood for
%	ordinal logistic regression model.

global stepr tol incr decr K Link;
beta=beta(:);

Kl=length(beta); 
zer=zeros(size(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

stepr= .001;
steprs=.000001;


% first derivative 

dl=[];
for k=1:Kl,
zerk=[]; zerk=zer; 
step=stepr*(k<(j+p))+steprs*(k>=(j+p));
zerk(k)=step;
zerk1=beta+zerk;
zerk2=beta-zerk;
L1=[]; L2=[];

[L1, dev]   = lik(y, x, x1, zerk1, pr1);
[L2, dev]   = lik(y, x, x1, zerk2, pr1);

dlk=sum((L1-L2)./(2*step));
dl(k)=dlk;
end;

dl=dl';


% second derivative
d2=[];

for j=1:Kl,
stepj=stepr*(j<(j+p))+steprs*(j>=(j+p));
zerj=zer; zerj(j)=stepj;

for k=1:Kl,
stepk=stepr*(k<(j+p))+steprs*(k>=(j+p));
zerk=zer; zerk(k)=stepk;

zerk1=beta+zerj+zerk; 
zerk2=beta+zerj-zerk; 
zerk3=beta-zerj+zerk; 
zerk4=beta-zerj-zerk; 
L1=[]; L2=[]; L3=[]; L4=[];
[L1,dev]=lik(y,x,x1,zerk1,pr1);
[L2,dev]=lik(y,x,x1,zerk2,pr1);	
[L3,dev]=lik(y,x,x1,zerk3,pr1);	
[L4,dev]=lik(y,x,x1,zerk4,pr1);	
d2l(j,k)=(L1-L2-L3+L4)./(4*stepk*stepj);
end;
end;






