*! version 1.1  Joseph Hilbe 11-27-95; revised 12-7-95
* Williams procedure to accomodate overdispersed grouped logistic models

program define williams
  version 4.0
  local varlist "req ex"
  #delimit ;
  local options "`options' LTolera(real -1) PHI(real 1.0) NOLog  RESidual
      EForm LEvel(integer $S_level) SCale(string)";
  #delimit cr
  local in "opt"
  local if "opt"
  parse "`*'"
  parse "`varlist'", parse(" ")
  qui {
  tempvar ocdisp dev alphap w alpha
  if `ltolera'<0 { local ltolera .0001 }
  local y "`1'"
  mac shift
  local den "`1'"

  _binom `y' `*', g
  local pdisp = $S_6
  gen `alpha'= 1/$S_6
  local j = 1
  local ddisp = 1
  gen `ocdisp'=1
  gen `dev'=1
  gen `alphap' =`alpha'
  gen `w' = 1
  while ((abs(`ddisp')) >= `ltolera') {
    replace `ocdisp' = $S_6
    local alpha = `alphap'
    _binom `y' `*', g phi(`alpha')
    replace `alphap'=$S_6 * $S_3
    if "`nolog'"=="" {
        noi di "j = " `j' "    phi = " `alpha' "    disp = " $S_6
    }
    local ddisp = $S_6 - `ocdisp'
    local j = `j'+1
  }
  tempvar wgt
  gen `wgt' = 1/(1+(`den'-1)*`alphap')
  noi _binom `y' `*' [fw=`wgt'] `if' `in', g nolog t `residual' /*
     */ `eform' level(`level')
  noi di in gr "Phi            =  " in ye %9.0g `alphap'
  if"`residual'"!="" {
  noi di in gr _n "Variables created:  "
  noi di in ye " _mu (fit),                  _lp (linear predictor)"
  noi di in ye " _Pear (Pearson resid),      _Dev (deviance resid)"
  noi di in ye " _Anscom (Anscombe resid),   _Hat (hat matrix diag.)"
  noi di in ye " _StandP (standard Pearson), _StandD (standard deviance)"
  }
}
end