*! version 1.1.0 Michael Lichter 04feb2010estimation sample
* limited predictions to estimation sample, used actual # of deciles instead of 10
* for # of groups, fixed temporary variables and names, various tinkering steps
* version 1.0.0 Kellie Arhcer 01jan2006
version 10.0
program define svylogitgof

	local pgm svylogitgof

		// no arguments
	if "`1'" != "" {
		di as error "`pgm' takes no arguments"
		error
	}

		// only svy logit or logistic
	else if (e(prefix) !=" svy") & ! ((e(cmd) == "logit") ///
			| (e(cmd) == "logistic")) {
		di as error "`pgm' only valid for svy: logit and svy: logistic"
		error 109
	}

	else quietly {

		tempvar touse phat decile resid
		tempname chivalm estbank

		local N = e(N)
		local df = e(N_psu) - e(N_strata)
		local G 10	// # of groups
		local wexp = e(wexp)
		local wexp = cond("`wexp'" == "", "", "[ pw `wexp' ]")
		local depvar = e(depvar)

			// limit to estimation sample
		mark `touse' if e(sample)
		svymarkout `touse'		// should not be needed

			// create residuals and deciles of "risk"
		predict double `phat' if `touse', pr
		gen double `resid' = `depvar' - `phat' if `touse'
		xtile byte `decile' = `phat' `wexp', nquantiles(`G')
		local g = r(N) + 1		// actual # of groups

			// calc mean residual by decile of prediction
			// (may not be deciles per depending on ties)
			// hold svy: logit estimates to restore at end
		_estimates hold `estbank', restore
		svy, over(`decile'): mean `resid'

			// e(b) is row-vector of decile means
		matrix `chivalm' = e(b) * inv(e(V)) * e(b)'

				// calc f-adjusted stat and p-value
		local Fadjm= `chivalm'[1,1] * ((`df' - `g' + 2) / (`df' * `g'))
		local FadjmP= Ftail(`g' - 1, `df' - `g' + 2, `Fadjm')

		noi di as text "   Number of observations = " _cont
		noi di _col(50) as result %10.0f `N'
		noi di as text "F-adjusted test statistic = " _cont
		noi di as text "F(" `g' - 1 "," `df' - `g' + 2 ") = " _cont
		noi di _col(50) as result %10.3f `Fadjm'
		noi di as text "                 Prob > F = " _cont
		noi di _col(50) as result %10.3f `FadjmP'
	}
end