/* eov_probit.g */
/* Program to calculate "errors-in-variables probit" estimates */

/* Create three matrices */

/* y (n by 1) as the dependent binary variable */

/* z (n by k) as explanatory variables with measurement errors */
/* (no column of ones should be included - you always get an intercept) */

/* par0 (k+1 by 1) as an initial estimate */
/* (create par0 for example from the probit estimate of y on z) */
/* (the first element is the intercept) */

/* Set pmat to reflect the reliability ratio that you want to use */

new;
load z,y,par0;
nobs = rows(z);
k = cols(z);

pmat = ones(k,k);
/* Change pmat here, for example pmat[2,2] = 0.9; */

mu = meanc(z);
sigz = vcx(z);
m1 = pmat.*sigz;
m2 = m1*inv(sigz);
m3 = (z-mu')*m2;
m4 = m2*m1;
dum = ones(n,1);

proc lfprobeov(par,dum);
local al,bl,mui,sigst;
al = par[1]; 
bl = par[2:k+1];
mui = al + bl'mu + m3*bl;
sigst = sqrt(bl'm1*bl - bl'm4*bl + 1); 
retp(sumc(y.*lncdfn(mui/sigst) + (1-y).*lncdfnc(mui/sigst)));
endp;

proc dprobeov(par,dum);
local al,bl,mui,sigst,v1,v2,mud,sigstd,ratd;
al = par[1]; 
bl = par[2:k+1];
mui = al + bl'mu + m3*bl;
sigst = sqrt(bl'm1*bl - bl'm4*bl + 1);
v1 = y.*pdfn(mui/sigst)./cdfn(mui/sigst);
v2 = -(1-y).*pdfn(mui/sigst)./(1-cdfn(mui/sigst));
mud = mu' + m3;
sigstd = (m1*bl - m4*bl)/sigst;
ratd = mud/sigst - mui*(sigstd')/(sigst^2);
ratd = (ones(nobs,1)/sigst)~ratd;
retp((sumc(ratd.*v1)+sumc(ratd.*v2))');
endp;

_max_GradProc  = &dprobeov;

_max_Algorithm = 4;


{par,f,g,cov,retcode} = maxprt(maxlik(dum,0,&lfprobeov,par0));

