************************************************************************************************************
* Stata program : mmsrm
* Estimate the parameters of the Multidimensional Marginally Sufficient Rasch Model (MMSRM)
* Release 2 : May 26, 2004
*
* Historic :
* Version 1 (May 14, 2004) [Jean-Benoit Hardouin]
*
* Jean-benoit Hardouin, Regional Health Observatory of Orléans - France
* jean-benoit.hardouin@neuf.fr
*
* Use the Stata programs raschtest and gammasym who can be download on http://anaqol.free.fr
* Use the Stata program gllamm who can be obtained by :  ssc install gllamm
* News about this program :http://anaqol.free.fr
*
* All the necessary programs on the FreeIRT Project website : http://freeirt.free.fr
*
* Copyright 2004 Jean-Benoit Hardouin
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*
************************************************************************************************************


program define mmsrm,eclass
version 8.0
syntax varlist(min=3 numeric) [, PARTition(numlist) NODETails TRAce]
preserve

local nbitems : word count `varlist'
if "`part'"=="" {
   local part=`nbitems'
}
local nbpart:word count `partition'

if `nbpart'== 1 {
   raschtest `varlist', notest mml
}
else if `nbpart'>2 {
     di in red "The mmsrm module do not run models with more than two dimensions for the moment."
}
if `nbpart'!=2 {
     exit
}

local comptitems=0
tokenize `varlist'
forvalues i=1/`nbpart' {
	local firstpart`i'=`comptitems'+1
	local part`i': word `i' of `partition'
	local set`i'
	local comptitems=`comptitems'+`part`i''
	forvalues j=`firstpart`i''/`comptitems' {
		local set`i' "`set`i'' ``j''"
	}
}

if `comptitems'<`nbitems' {
	di in error "Your partition describe less items than the number of items defined in the varlist."
	di in error "Correct your code."
	exit
}
if `comptitems'>`nbitems' {
	di in error "Your partition describe more items than the number of items defined in the varlist."
	di in error "Correct your code."
	exit
}


forvalues i=1/`nbpart' {
	if "`details'"=="" {
		di in green "Estimation of the difficulty parameters of the dimension `i'."
	}
        *set trace on
	if `part`i''>1 {
	   qui raschtest `set`i'',mml notest
	   tempname beta`i' Varbeta`i'
	   matrix `beta`i''=e(beta)
	   matrix `Varbeta`i''=e(Varbeta)
	   local sigma`i'=e(sigma)
	   forvalues j=1/`part`i'' {
		local parambeta`=`firstpart`i''+`j'-1'=`beta`i''[1,`j']
           }
	}
        else {
           qui count
           local N=r(N)
           qui count if ``firstpart`i'''==1
           local pos=r(N)
           local parambeta`firstpart`i''=-log(`pos'/(`N'-`pos'))
           local sigma`i'=0
        }
}


if "`details'"=="" {
	di
	di in green "Estimation of the parameters of the distribution of the multidimensional latent trait."
	di in green "This process could be long to run. Be patient !"
}

*set trace on
tempfile savemmsrm
qui save `savemmsrm'
keep `varlist'

tempname rep id item offset
forvalues i=1/`nbitems' {
	rename ``i'' `rep'`i'
}

gen `id'=_n
qui reshape long `rep', i(`id') j(`item')

gen `offset'=0
label variable `offset' "offset"

forvalues i=1/`nbitems' {
	qui replace `offset'=-`parambeta`i'' if `item'==`i'
}

local eqs
forvalues i=1/`nbpart' {
	tempname B`i'
	gen `B`i''=0
	eq sc`i':`B`i''
	local eqs `eqs' sc`i'
	forvalues j=`firstpart`i''/`=`firstpart`i''+`part`i''-1' {
		qui replace `B`i''=1 if `item'==`j'
	} 
}

label variable `rep' "response"
label variable `id' "identifiant"

tempname first
local four=substr("`id'",1,3)
matrix define `first'=(0,`sigma1',`sigma2',0)
matrix colnames `first'=`rep':_cons `four'1_1:`B1' `four'1_2:`B2' `four'1_2_1:_cons

if "`trace'"!="" {
     local quigllamm
}
else {
     local quigllamm qui
}

`quigllamm' gllamm `rep', from(`first') link(logit) fam(bin)  i(`id')  offset(`offset') nrf(`nbpart') eqs(`eqs')  nip(5) dots `trace'
local AIC=-2*e(ll)+2*(`nbitems'+`nbpart'*(`nbpart'+1)/2)
local ll=e(ll)
tempname cosig varsig L M
matrix `cosig'=e(b)
matrix `varsig'=e(V)
matrix `L'=e(chol)
matrix `M'=`L'*`L''

forvalues i=1/`nbpart'{
}

if `nbpart'==2 {
	local var1=`M'[1,1]
	local var2=`M'[2,2]
	local sevar1=(sqrt(`varsig'[2,2])*2*sqrt(`var1'))
	local sevar2=.

	local cov12=`M'[1,2]
	local secov=.

di
di in green _col(4) "Log-likelihood:" in yellow %-12.4f `ll'
di
noi di in green _col(4) "Items" _col(16) "Parameters" _col(29) "std Err."
di in green _col(4) "{hline 33}"
forvalues i=1/`part1' {
         if `part1'!=1 {
            noi di in yellow _col(4) "``i''" _col(18) %8.5f `beta1'[1,`i'] _col(30) %6.5f sqrt(`Varbeta1'[`i',`i'])
         }
         else {
            noi di in yellow _col(4) "``i''" _col(18) %8.5f `parambeta`firstpart1'' _col(30) "."
         }
}
di in green _col(4) "{hline 33}"
forvalues i=`firstpart2'/`=`part1'+`part2'' {
         if `part2'!=1 {
            noi di in yellow _col(4) "``i''" _col(18) %8.5f `beta2'[1,`=`i'-`part1''] _col(30) %6.5f sqrt(`Varbeta2'[`=`i'-`part1'',`=`i'-`part1''])
         }
         else {
            noi di in yellow _col(4) "``i''" _col(18) %8.5f `parambeta`firstpart2'' _col(30) "."
         }
}
di in green _col(4) "{hline 33}"
forvalues i=1/`nbpart' {
          noi di in yellow _col(4) "Var`i'" _col(18) %8.5f `var`i'' /*_col(30) %6.5f `sevar`i''*/
}
di in green _col(4) in yellow "cov12" _col(18) %8.5f `cov12' /*_col(30) %6.5f `secov'*/
di in green _col(4) "{hline 33}"
}
if "`trace'"=="" {
                 di in green "Add the trace option to obtain the standard errors of the elements"
                 di in green "of the covariance matrix of the latent traits"
}

ereturn clear
ereturn scalar AIC=`AIC'
ereturn scalar ll=`ll'
ereturn scalar dimension=`nbpart'
forvalues i=1/`nbpart' {
	ereturn scalar nbitems`i'=`part`i''
	ereturn local set`i' `set`i''
	if `part`i''>1 {
		ereturn matrix beta`i'=`beta`i''
	        ereturn matrix Varbeta`i' `Varbeta`i''
	}
	else  {
		ereturn scalar beta`i'=`parambeta`firstpart`i'''
        }
}

*ereturn matrix cosig=`cosig'
*ereturn matrix varsig=`varsig'

tempname matrixsigma
matrix `matrixsigma'=(`sigma1',`sigma2',`cov12')
matrix colnames `matrixsigma'= sigma1 sigma2 cov12
ereturn matrix sigma=`matrixsigma'

drop _all
qui use `savemmsrm'
end
